Reputation: 41
In Laravel, i have 2 table:
post table:
╔════╦══════════════╦══════╗
║ ID ║ CONTENT ║USERID║
╠════╬══════════════╬══════╣
║ 1 ║ Lorem 1 ║ 1 ║
║ 2 ║ Lorem 2 ║ 3 ║
║ 3 ║ Lorem 3 ║ 1 ║
║ 4 ║ Lorem 4 ║ 2 ║
╚════╩══════════════╩══════╝
And user table:
╔════╦════════════════╗
║ ID ║ EMAIL ║
╠════╬════════════════║
║ 1 ║[email protected] ║
║ 2 ║[email protected] ║
║ 3 ║[email protected] ║
║ 4 ║[email protected] ║
╚════╩════════════════╝
I want to select all posts posted by user ID using Laravel. Post, User Model:
#Post Model
class Post extends \Eloquent {
public function user()
{
return $this->belongsTo('User', 'userid');
}
}
#User Model
class User extends \Eloquent {
public function post()
{
return $this->hasMany('Post');
}
}
Now, I was select using Laravel Eloquent:
$post = Post::with(array(
'user' => function($query)
{
$query->where('email', Input::get('email'));
}
))->paginate(10);
This code will select all post, not by user, and paginate wrong page. Anyone can help me ? Thanks so much !
Upvotes: 0
Views: 389
Reputation: 219920
You're looking for the whereHas
method:
$posts = Post::whereHas('user', function($query)
{
$query->where('email', Input::get('email'));
})->paginate(10);
Upvotes: 1