问题
I have a many-to-many laravel relationship for posts and topics:
- Posts belongstoMany Topics
- Topics belongstoMany Posts
I want to get posts with id > 10 from a certain topic
The following code will get me all the posts from certain topic:
$topic = Topic::where('id',$topic_id)->get()->first();
$posts= $topic->post;
Now how to get posts with id > 10 ?
Models:
class Topic extends Eloquent{
public function post()
{
return $this->belongsToMany('post');
}
}
class Post extends Eloquent{
public function topic()
{
return $this->belongsToMany('Topic');
}
}
回答1:
Like this:
Topic::with(array('posts' => function($q)
{
$q->where('id', '>', 10);
}))->where('id', $id)->first();
回答2:
If you want to apply Where
clause to belongsToMany
Here is where condition
$permissions = Role::with('getRolePermissions')->where('id', '=', Auth::guard('admin')->user()->id)->get()->toArray();
In this URL getRolePermissions
is the model function, Inside it I have used the Many To Many relationship
public function getRolePermissions() {
return $this->belongsToMany('App\Permission', 'permission_role');
}
回答3:
you should do like this
$topic = Topic::find($topic_id);
$posts= $topic->posts()->where('id','>',10)->get();
or
$posts = Topic::find($topic_id)->posts()->where('id','>',10)->get();
hope this help
来源:https://stackoverflow.com/questions/19745512/laravel-selecting-with-conditions-from-many-to-many-relationships