Laravel 当我';我正在使用即时加载进行查询?
我有一些表,其中一个表名为Laravel 当我';我正在使用即时加载进行查询?,laravel,Laravel,我有一些表,其中一个表名为Users,其中有软删除行 我有如下代码: $appointments = Appointment::with('user')->get(); $return = array(); foreach ($appointments as $key => $appointment) { $return[] = array( $appointment->customer_name, $appointment->d
Users
,其中有软删除行
我有如下代码:
$appointments = Appointment::with('user')->get();
$return = array();
foreach ($appointments as $key => $appointment) {
$return[] = array(
$appointment->customer_name,
$appointment->date->format('d/m/Y'),
$appointment->time,
$appointment->status,
$appointment->user->full_name,
);
}
由于删除了包含该用户的行,因此在以下行中出现错误:
$appointment->user->full_name
因为这个用户当然不匹配
我尝试将withTrashed()添加到第一行,在之前和之后都使用('user')
添加,但没有效果
如何确保此查询确实返回所有用户的所有约会,甚至是已删除的约会?我不能100%确定此方法是否有效,因为此方法旨在为即时加载添加约束,但您可能希望尝试:
$appointments = Appointment::with(array('user' => function($query) {
$query->withTrashed();
}))->get();
withTrashed()应该应用于抓取用户的查询,而不是抓取约会的查询
哦,为了澄清一下,您可以将withTrashed()添加到两个查询中:
$appointments = Appointment::with(array('user' => function($query) {
$query->withTrashed();
}))->withTrashed()->get();
编辑:只是想到了一个更简单的方法: 将withTrashed()添加到user()关系(仅当您希望每次调用此关系时都应用此选项时才执行此操作):
对于最后一个解决方案:我会为它创建一个单独的方法,称为
trashedUser()
,这样你也可以使用原来的方法。通过谷歌搜索找到了这个方法。可以证实至少第一种方法工作出色。谢谢。:)
public function user() {
return $this->hasOne('User')->withTrashed();
}