我的查询:
Description::whereHas('expenses', function($query) {
$query->where('date', $this->date);
})->with('expenses')->get();
上述查询返回给定日期的所有描述,但它返回该描述的所有费用,而不是给定日期的费用。我不明白为什么会这样,我想首先理解这一点。这是因为with('expenses')
我只是急于为每个描述加载所有费用吗?有了whereHas我只返回给定日期至少有一笔费用的所有描述?
如果以上所有情况都属实,我如何返回给定日期的所有描述,包括给定日期的费用?
描述型号:
public function expenses()
{
return $this->hasMany(Expense::class);
}
费用模型:
public function description()
{
return $this->belongsTo(Description::class);
}
答案 0 :(得分:1)
您只是过滤应加载哪些Description
个对象。您应该将相同的过滤器应用于预先加载,以便只将这些过滤器添加到模型中。
Description::whereHas('expenses', function($query) {
$query->where('date', $this->date);
})
->with([
'expenses' => function($query) {
$query->where('date', $this->date);
}
])
->get();