Laravel 嵌套的;带();拉维尔

Laravel 嵌套的;带();拉维尔,laravel,eloquent,Laravel,Eloquent,我和一些关系有问题。我有以下情况 产品: public function catalogues() { return $this->belongsToMany('App\Catalogue'); } public function category() { return $this->belongsTo('App\Category'); } 类别: public function products() { return $this-&

我和一些关系有问题。我有以下情况

产品:

public function catalogues()

 {
     return $this->belongsToMany('App\Catalogue');
 }

public function category()
{
    return $this->belongsTo('App\Category');
}
类别:

 public function products()
   {
       return $this->hasMany('App\Product');
   }
目录:

    public function products()
   {
       return $this->belongsToMany('App\Product');
   }

通过一个查询,我需要得到所有类别的产品属于某个目录。我怎样才能做到呢

您需要
在哪里

    Category::whereHas('products')
  ->with(['products' => function($query) use ($id){
        $query->with('catalogues' => function($query) use ($id){

         $query->where('catalogues.id',$id);

      });

   }])
  ->get();
希望这有帮助。

使用
wherehads()

或:


你需要谢谢你,但实际上我以后需要做的是按类别循环,而不是按产品循环。这就是为什么我有点困惑的原因,因为我尝试了“with”方法,如果我只是挑选产品,而不是加入目录,这是非常有效的,因为b/w目录和categories@Dani我已经更新了答案,看一看。它可能会帮助你惊人的,这工作!谢谢你,你救了我的头疼:)@Dani我很高兴这对你有用。如果这真的对您有效,您可以接受这个答案。@Dani这不可能对您有效,因为此代码将给您一个错误,
with()
将加载数据,而不是按相关数据筛选类别。这也不起作用,它将检索这些类别中的所有产品。@Dani它无法检索任何产品,它将只返回类别。不要修改代码,按原样使用。谢谢。在Laravel背包中,我能够使用
$this->crud->query=$this->crud->query->whereHas('contactTags',函数($q)use($tagId){$q->where('tag_id',$tagId);})
Category::whereHas('products.catalogues', function($q) use($catalogueId) {
    $q->where('catalogues.id', $catalogueId);
})
->get();
Category::whereHas('products', function($q) use($catalogueId) {
    $q->whereHas('catalogues', function($q) use($catalogueId) {
        $q->where('id', $catalogueId);
    })
})
->get();