2017-01-16 89 views
1

我有一个树中彼此相关的类别。每个类别hasMany孩子。每个末端类别hasMany产品。laravel中的负载关系与关系的条件

该产品还有belongsToMany不同的类型。

我想急于加载与他们的孩子和产品类别,但我也想提出一个条件,产品是某种类型。

这是我的类模型看起来像

public function children() 
{ 
    return $this->hasMany('Category', 'parent_id', 'id'); 
} 


public function products() 
{ 
    return $this->hasMany('Product', 'category_id', 'id'); 
} 

的产品型号

public function types() 
{ 
    return $this->belongsToMany(type::class, 'product_type'); 
} 

在我的数据库中,我有四个表: 类别,产品,类型和产品类型

我已经尝试过这样急于加载,但它会加载所有产品,而不仅仅是满足条件的产品:

$parentLineCategories = ProductCategory::with('children')->with(['products'=> function ($query) { 
     $query->join('product_type', 'product_type.product_id', '=', 'product.id') 
      ->where('product_type.type_id', '=', $SpecificID); 
    }]])->get(); 

回答

1

而不是当前查询,尝试如果这符合您的需求。 (我修改我的回答您的评论如下)

$parentLineCategories = ProductCategory::with([ 
      'children' => function ($child) use ($SpecificID) { 
       return $child->with([ 
        'products' => function ($product) use ($SpecificID) { 
         return $product->with([ 
          'types' => function ($type) use ($SpecificID) { 
           return $type->where('id', $SpecificID); 
          } 
         ]); 
        } 
       ]); 
      } 
     ])->get(); 
+0

这仍然给了我所有的产品 – user3552551

+0

你是否在寻找与'子女'或父母'类别'有关的'产品' – Gayan

+0

请检查它是否不是数据问题。即属于同一个“父类别”的所有“产品” – Gayan

0

您可以使用whereHas基于一个关系的存在,以限制搜索结果:

ProductCategory::with('children') 
      ->with(['products' => function ($q) use($SpecificID) { 
       $q->whereHas('types', function($q) use($SpecificID) { 
        $q->where('types.id', $SpecificID) 
       }); 
      }]) 
      ->get();