Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all eloquent models without relationship

I would like to fetch all models that don't have a relationship.

Similar to fetching models which have one:

return $this->model->has('quote')->orderBy('created_at', 'desc')->get();

I would basically like to have the inverse of this. I can't find any documentation to do this though.

Basically this query:

SELECT * FROM custom_design_requests
RIGHT JOIN quotes
ON quotes.`custom_design_request_id` = `custom_design_requests`.id

But I'd like to avoid having to use the Query Builder (DB::table('custom_design_requests')->rightJoin('quotes', 'quotes.custom_design_request_id', '=', 'custom_design_requests.id')->get();), so that I have a collection of instances of the model.

Thanks

like image 436
Nicolas Widart Avatar asked Jul 21 '15 09:07

Nicolas Widart


Video Answer


2 Answers

I believe this is better than the accepted solution:

$this->model->doesntHave('quote')->orderBy('created_at', 'desc')->get();

This is described in more detail here:

https://laravel.com/docs/5.4/eloquent-relationships#querying-relationship-absence

like image 50
Yahya Uddin Avatar answered Sep 29 '22 16:09

Yahya Uddin


You may try something like this:

$this->model->has('quote', '<', 1)->orderBy('created_at', 'desc')->get();
like image 42
The Alpha Avatar answered Sep 29 '22 16:09

The Alpha