laravel 当我使用预先加载进行查询时如何使用 withTrashed?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21995670/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 02:44:49  来源:igfitidea点击:

How to use withTrashed when I'm querying using eager loading?

laravel

提问by Rich Bradshaw

I have some tables, one of which is a table named Userswhere there are soft deleted rows.

我有一些表,其中一个是一个名为表,Users其中有软删除的行。

I have code like:

我有这样的代码:

$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,
    );
}

Because the row with the user is deleted, I get an error on the line with:

因为用户所在的行被删除,我在行上收到一个错误:

$appointment->user->full_name

because of course there is no match for this user.

因为这个用户当然没有匹配项。

I tried adding withTrashed() to the first line, both before and after with('user')but this didn't help.

我尝试将 withTrashed() 添加到第一行之前和之后,with('user')但这没有帮助。

How do I ensure that this query really does return all appointments with all users, even deleted ones?

我如何确保此查询确实返回所有用户的所有约会,甚至是已删除的约会?

回答by TonyArra

I'm not 100% sure this works, as this method is meant for adding constraints to eager-loading, but you may want to try it:

我不是 100% 确定这有效,因为此方法旨在为预先加载添加约束,但您可能想尝试一下:

$appointments = Appointment::with(array('user' => function($query) {
    $query->withTrashed();
}))->get();

This should apply withTrashed() to the query that grabs the users as opposed to the query which grabs the appointments.

这应该将 withTrashed() 应用于获取用户的查询,而不是获取约会的查询。

Oh and just to clarify, you can add withTrashed() to both queries:

哦,为了澄清一下,您可以将 withTrashed() 添加到两个查询中:

$appointments = Appointment::with(array('user' => function($query) {
    $query->withTrashed();
}))->withTrashed()->get();


Edit: just thought of an easier method:

编辑:只是想到一个更简单的方法:

Add withTrashed() to the user() relationship (only do this if you want this to apply EVERY time you call this relationship):

将 withTrashed() 添加到 user() 关系(仅当您希望每次调用此关系时都应用此关系时才这样做):

public function user() {
  return $this->hasOne('User')->withTrashed();
}