Laravel: selecting with conditions from Many-to-many relationships

两盒软妹~` 提交于 2019-12-23 05:58:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!