laravel 获取所有没有关系的 eloquent 模型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31535024/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 11:59:49  来源:igfitidea点击:

Get all eloquent models without relationship

phplaravellaravel-5eloquent

提问by Nicolas Widart

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.

但我想避免使用查询生成器 ( DB::table('custom_design_requests')->rightJoin('quotes', 'quotes.custom_design_request_id', '=', 'custom_design_requests.id')->get();),这样我就有了模型实例的集合。

Thanks

谢谢

回答by The Alpha

You may try something like this:

你可以尝试这样的事情:

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

回答by Yahya Uddin

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

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

回答by jedrzej.kurylo

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 JOINyour model with quotes and take only those, for which there are no corresponding quotes.

这将使用引号LEFT JOIN您的模型并仅采用那些没有相应引号的模型。