How to return erased information with softdelete within a relation

Asked

Viewed 134 times

0

There is a model in my application called payment that belongs to a user. I pull the information with

Pagamento::latest()->with('user');

That way if a user is deleted, even if he already has soft delete, he is not returned. How to return it along with payments? So, basically I want to include users deleted by soft-delete in this query. Some way to put a withTrashed() for the user in this query.

2 answers

1

If you do not want that, whenever calling this relationship, it also brings the deleted records, as in case of adding withTrashes() when defining the relationship in the template, you can do it in the query:

Pagamento::with(['user' => function ($q) {
   $q->withTrashed();
}])->latest();

0

The problem was solved including ->withTrashed in relation.

In the Pagamento.php:

public function user()
{
    return $this->belongsTo('App\User')->withTrashed();
}
  • It has been solved and created another! If you can not delete user if he has relationship understands?

  • I don’t think @Virgilionovic because he is using Laravel softDelete, the user data will continue in the database, only the column deleted_at will be filled and this user will not be displayed within the system if he does not use this function of withTrashed

  • Yes @Kayobruno but, what was done in this reply limits the user to do only this way, it would be better to create a Scope query for this, or a relationship of his own.

  • @Virgilionovic I agree with you that creating a query Cope for this would be much better, I’m not saying you’re wrong I just didn’t understand when you said "limit the user to do only this way". kkkk

  • because generally @Kayobruno the relation function user is to bring users and you limit yourself with an extra query in the function. That’s it...

  • 1

    @Virgilionovic now understood, yes it really makes sense. Thank you for having clarified even though I took a long time to understand rsrsr.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.