Nicolas Widart
Nicolas Widart

Reputation: 1287

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

Upvotes: 11

Views: 21886

Answers (3)

Yahya Uddin
Yahya Uddin

Reputation: 28891

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

Upvotes: 17

The Alpha
The Alpha

Reputation: 146219

You may try something like this:

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

Upvotes: 14

jedrzej.kurylo
jedrzej.kurylo

Reputation: 40919

Try:

return $this->model
  ->leftJoin('quotes', 'quotes.custom_design_request_id', '=', 'custom_design_requests.id')
  ->whereNull('quotes.custom_design_request_id')
  ->orderBy('created_at', 'desc')->get();

This will LEFT JOIN your model with quotes and take only those, for which there are no corresponding quotes.

Upvotes: 3

Related Questions