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

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.

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

没有正确的解决方案

其他提示

withTrashed() can be applied to the query that retrieves the users like so:

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

You can also apply withTrashed() to both the appointment and their users:

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

Alternatively, you can add withTrashed() to the association method to apply it whenever the association is loaded:

public function user() {
  return $this->hasOne('User')->withTrashed();
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top