laravel 使用laravel eloquent关系检索除NULL以外的所有记录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33759750/
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 12:42:23  来源:igfitidea点击:

Using laravel eloquent relation to retrieve all records except NULL

phplaravel

提问by user3641381

Is there a way to retrieve all the records which has not null using eloquent model.

有没有办法使用 eloquent 模型检索所有不为空的记录。

e.g.

例如

I have relation setup

我有关系设置

Plate model

板型

public function project()
{
    return $this->hasOne('App\Models\Project');
}

project model

项目模型

public function plate()
{
    return $this->belongsTo('App\Models\Plate');
}

How can I retrieve all the records which have value.

如何检索所有有价值的记录。

trying this return $p = \App\Models\Plate::with('project')->get();

试试这个 return $p = \App\Models\Plate::with('project')->get();

will return everything, even those who have NULL.

将返回一切,即使是那些拥有NULL.

enter image description here

在此处输入图片说明

All I want is plateswhich have projects attached to. I tried laravel documentation, but could't find anything. Is there also same approach for manyrelations

我想要的只是plates附有项目。我尝试了 laravel 文档,但找不到任何内容。是否也有相同的many关系 方法

回答by Thomas Kim

You can use the hasmethod to only retrieve plates that have a project.

您可以使用该has方法仅检索具有项目的板。

\App\Models\Plate::with('project')->has('project')->get();

Docs on has: http://laravel.com/docs/5.1/eloquent-relationships#querying-relations

文档hashttp: //laravel.com/docs/5.1/eloquent-relationships#querying-relations