【问题标题】:How to make multi table eloquent query in laravel 8?如何在 laravel 8 中进行多表 eloquent 查询?
【发布时间】:2021-02-20 19:26:42
【问题描述】:

我有两个模型,分别命名为“Products”和“Product_options”,每个产品都有很多选项。

我想选择那些至少有一个选项为真的产品。

我已经走了这么远,

class Product extends Model
{
    use HasFactory;
    
    public function options()
    {
        return $this->hasMany(Product_options::class, 'product_id', 'id');
    }
}
$products = Product::whereDoesntHave('options', function ($query) {
                $query->where('available','not', ' 1');
                })
           ->has('options', '>',  0)
           ->get();

dd($products);

但如果一个产品有一个或多个选项,其中 avaible 为真,而一个或多个选项为假,则不会选择产品。

附言对不起我的英语。

【问题讨论】:

  • 欢迎来到SO ...你的英语很好,可能比一些母语人士更好:)

标签: php laravel eloquent laravel-8


【解决方案1】:

您应该可以使用whereHas。计数默认为>= 1

Product::whereHas('options', fn ($q) => $q->where('available', true))
    ->get();

应理解为,获取所有具有“可用”为“真”选项的所有产品。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-21
    • 1970-01-01
    • 2019-12-19
    • 2013-04-24
    • 2017-10-24
    相关资源
    最近更新 更多