【问题标题】:Eager load relationships in laravel with conditions on the relationlaravel中的急切负载关系以及关系上的条件
【发布时间】:2017-05-31 11:47:20
【问题描述】:

我在树中有彼此相关的类别。每个类别hasMany儿童。每个终端类别hasMany 产品。

产品还有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();

【问题讨论】:

    标签: php laravel eloquent


    【解决方案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();
    

    【讨论】:

    • 这仍然给了我所有的产品
    • 您在寻找与children 相关的products 或父category
    • 请检查是否不是数据问题。即所有product 属于同一个parent category
    • 我正在寻找与儿童类别相关的产品。我得到了很好的类别和他们的孩子类别。问题在于我希望根据约束加载它们的产品(它们属于我指定的类型)。到目前为止,我得到了一个子类别的所有产品。我想过滤那个结果。
    • 这有帮助吗?
    【解决方案2】:

    您可以使用whereHas 根据是否存在以下关系来限制您的结果:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-09
      • 1970-01-01
      • 1970-01-01
      • 2020-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多