我想通过关系来使用订单获取数据:
return $this->customer->where('status', 1)
->whereDoesntHave('activeAssignments')
->with('latestDismissal')
->join('dismissal', 'customers.id', '=', 'dismissal.customer_id')
->orderBy('dismissal.valid_at_timestamp')
->paginate(config('app.pagination'));
但是,如果我运行此代码,则客户模型中的自定义访问器将不再起作用:
Trying to get property 'last_name' of non-object
为此访问者:
public function getDisplayNameAttribute()
{
if (!$this->toCareFirst()->first()->last_name) {
return 'NO NAME';
}
return trim(
$this->toCares()->get()->implode('display_name', ' & ')
);
}
如果我在查询中添加>select('customers.*')
,它将返回我的数据,但相同的数据将返回4或5次...
答案 0 :(得分:1)
您可以使用修改后的withCount()
:
return $this->customer->where('status', 1)
->whereDoesntHave('activeAssignments')
->with('latestDismissal')
->withCount(['latestDismissal as dismissal_order' => function($query) {
$query->select('valid_at_timestamp')->latest('id')->limit(1);
}])
->orderBy('dismissal_order')
->paginate(config('app.pagination'));