【问题标题】:Product not shown with relation in Laravel产品未在 Laravel 中与关系显示
【发布时间】:2021-03-20 22:48:22
【问题描述】:

我有这两张桌子:

一个是产品表:

id Title Price
1 Title 1 5000
2 Product 2 7000

另一个是产品属性表:

id product_id attribute_id attribute_name value
1 1 5 Color Red
2 1 6 Size XL
3 2 5 Color Green

产品和产品属性与以下关系相关(在产品模型中):

 public function attributes()
    {
        return $this->hasMany(ProductsAttribute::class, 'product_id ');
    }

我正在获取这样的数据:

return Product::with('attributes')
        ->whereHas('attributes', function ($query) use ($attribute_id,$attribute_value){
            $query->whereIn('attribute_id', $attribute_id);
            $query->whereIn('value', $attribute_value);
        })
        ->paginate(10);

问题是如果产品属性表中没有与特定产品相关的属性,则该产品不会显示在搜索中,但我的要求是如果相关属性不存在,那么产品也应显示在结果。

非常感谢任何帮助。

【问题讨论】:

  • 作为旁注,使用名称attributes时要小心;模型已经有一个属性$model->attributes,它是一个由它们的数据库列组成的数组,并且命名一个关系public function attributes() 可能会产生意想不到的副作用。

标签: laravel laravel-5 eloquent


【解决方案1】:

您正在使用whereHas 中的约束,这就是为什么它会从条件评估为假的结果中排除产品记录。

试试

return Product::with(['attributes' => function ($query) use ($attribute_id,$attribute_value){
            $query->whereIn('attribute_id', $attribute_id)
                ->whereIn('value', $attribute_value);
        })
        ->paginate(10);

【讨论】:

    猜你喜欢
    • 2018-08-22
    • 1970-01-01
    • 2017-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多