Laravel 4.2 : add soft deleted items to whereHas condition

1.1k views Asked by At

I have an issue on Laravel 4.2 and found no solution on my Google friend : I want to get all soft deleted items in a whereHas condition and it doesn't work at all...

Here is the code :

$res = $this->model->whereHas('dsps', function ($q) use ($dsp_id) {
                $q->where('dsps.id', $dsp_id);
                $q->withTrashed();
})->get();

And I get the following SQL request :

select * from `bdc` where (select count(*) from `dsps` inner join `bdc_dsp` on `dsps`.`id` = `bdc_dsp`.`dsp_id` where `bdc_dsp`.`bdc_id` = `bdc`.`id` and `dsps`.`id` = 81 and `dsps`.`deleted_at` is null) >= 1;

The problem is clearly that the "deleted_at is null" remains. It should disappear by using the withTrashed() method.

I tried to put the withTrashed() like that :

$q->where('dsps.id', $sst_dsp)->withTrashed();

and it doesn't changes anything.

How could make that "deleted_at is null" condition from my whereHas request with an elegant solution ? Thank by advance for your advices !

1

There are 1 answers

1
ceejayoz On BEST ANSWER

One solution to this is creating an alternate form of the relationship that includes trashed records.

public function dspsTrashed() {
  return $this->hasWhatever()->withTrashed();
}

Then:

$this->model->whereHas('dspsTrashed', ...);