Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

withTrashed on hasManyThrough relation

How can withTrashed be applied on a hasManyThrough relation ?

$this->hasManyThrough('App\Message', 'App\Deal')->withTrashed();

returns

Call to undefined method Illuminate\Database\Query\Builder::withTrashed()

when i'm doing:

$messages = Auth::user()->messages()->with('deal')->orderBy('created_at', 'DESC')->get();`

Here is my Deal model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Deal extends Model
{

    use SoftDeletes;

    /* ... */

    protected $dates = ['deleted_at'];

    public function user() {
        return $this->belongsTo('App\User');
    }

    public function messages() {
        return $this->hasMany('App\Message'); // I've tried to put withTrashed() here, there is no error but it doesn't include soft deleting items.
    }
}
like image 673
Neabfi Avatar asked Jun 10 '17 18:06

Neabfi


2 Answers

To all those coming to this late, there is now a native way of doing this with Laravel.

$this->hasManyThrough('App\Message', 'App\Deal')->withTrashedParents();

This is not well documented but can be found in Illuminate\Database\Eloquent\Relations\HasManyThrough

like image 145
Spholt Avatar answered Jan 02 '23 06:01

Spholt


The error is thrown because you are requesting a messages with deleted ones without using SoftDelete trait in Message model.

After I check the hasManyThrough relation code I found that there is no way to do it in this way, you should play around.

Ex:

get the deals of user with messages instead

$deals = Auth::user()->deals()->withTrashed()->with('messages')->get();
foreach($deals as $deal) {
     //Do your logic here and you can access messages of deal with $deal->messages
} 
like image 23
Aboudeh87 Avatar answered Jan 02 '23 07:01

Aboudeh87