【发布时间】:2016-12-17 22:16:03
【问题描述】:
我发现with 函数用于重载关系的一个非常奇怪的行为。我有Product 和Deal 关系,例如Product belongsTo() Deal(通过product_id 在deals 表中)。现在,当我尝试让所有产品都打折时:
Product::with(['deal' => function($query) {
$query->whereDate('ends_at', '>', Carbon::now()->toDateTimeString());
}])->get()
这会返回所有产品的集合,即使deals 表中没有没有记录并且所有产品有deal_id设置为NULL。同时Product::has('deal')->get() 返回一个空集合,正如您所期望的那样。
我最初在尝试获取 5 个随机销售的产品以及 Deal 和 Image 关系时发现了这个问题:
Product::with(['deal' => function ($query) {
$query->whereDate('ends_at', '>', // promo still active
Carbon::now()->toDateTimeString());
},
'images' => function ($query) {
$query->where('featured', true); // image featured on homepage
}])
->where('status', 'IN_STOCK') // 'In Stock'
->whereNull('deleted_at') // wasn't soft-deleted
->orderByRaw('RAND()')
->take(5)->get())
这会产生一个集合,其中包含所有 Products 中的 5 个随机 Products。我尝试了query->whereNotNull('ends_at')->whereDate('ends_at' ..... );,但得到了相同的结果。
我在这里做错了什么?
【问题讨论】:
标签: laravel eloquent laravel-5.3