在使用紧急加载进行查询时,如何使用withTrashed? [英] How to use withTrashed when I'm querying using eager loading?

查看:94
本文介绍了在使用紧急加载进行查询时,如何使用withTrashed?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我有类似的代码:

$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.

我尝试在with('user')之前和之后的第一行中添加withTrashed(),但这无济于事.

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

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

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

推荐答案

我不是100%确信这可行,因为此方法旨在为急切加载添加约束,但您可能需要尝试一下:

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:

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

这应该与withTrashed()一起应用于捕获用户的查询,而不是捕获约会的查询.

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:

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


只是想到了一种更简单的方法:


just thought of an easier method:

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

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

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

这篇关于在使用紧急加载进行查询时,如何使用withTrashed?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆