Laravel 检查关系是否为空

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

Laravel check if relation is empty

laravelrelationship

提问by Jessy

I have an object with some relationships and I need to check if these relations are empty or not, I'm trying to check with is_null, isset, != undefined, etc but nothing works, here is the relationship I get when it's empty :

我有一个具有某些关系的对象,我需要检查这些关系是否为空,我正在尝试使用 is_null、isset、!= undefined 等进行检查,但没有任何效果,这是我在为空时得到的关系:

object(Illuminate\Database\Eloquent\Collection)#197 (1) {
  ["items":protected]=>
    array(0) {
  }
}

Is there a way to check this easily ? Thanks.

有没有办法轻松检查这个?谢谢。

回答by Devon

There are a variety of ways to do this.

有多种方法可以做到这一点。

In the query itself, you can filter models that do not have any related items:

在查询本身中,您可以过滤没有任何相关项的模型:

Model::has('relation')->get()

Once you have a model, if you already have loaded the collection, you can check the count of the collection:

一旦你有了一个模型,如果你已经加载了集合,你可以检查集合的数量:

$model->relation->count();

If you want to check without loading the relation, you can run a query on the relation:

如果您想在不加载关系的情况下进行检查,可以对关系运行查询:

$model->relation()->exists()

Note:Replace relationwith the name of your relationship in the above examples.

注意:relation在上述示例中替换为您的关系名称。

回答by Calos

If model already have loaded relationship, you can determine the variable is nullor call isEmpty()to check related items:

如果模型已经加载了关系,你可以确定变量是null或调用isEmpty()检查相关项:

// For one relation:
if ( $model->relation ) {
    // ...
} else {
    // $model->relation is null
}

// For many relations:
if ( $model->relation->isEmpty() ) {
    // ...
}

回答by Patrick.SE

This doesn't directly answer the question, but you can use Laravel's optionalhelper to call methods on a relationship you suspect might not have a value:

这并不能直接回答问题,但您可以使用 Laravel 的optional助手来调用您怀疑可能没有值的关系的方法:

optional($user->comments)->where('is_popular', true);

If the user doesn't have comments, this will return null. Otherwise it will return the user's popular comments.

如果用户没有评论,这将返回 null。否则,它将返回用户的热门评论。

回答by Yevgeniy Afanasyev

First, you might want to check if your Relationis loaded

首先,您可能想检查是否Relation已加载

if ($user->relationLoaded('posts'))...

second, when it is loaded, you might want to see if it is an empty Collectionor Null,

第二,当它被加载时,你可能想看看它是空的Collection还是Null,

if ($user->posts()->exists())...

PS

聚苯乙烯

use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Database\Eloquent\Collection;

回答by pardeep

    $model->relation()->exists()
if (count($model->relation))
{
  // check exists
}

also 2nd method

还有第二种方法

if(!is_null($model->relation)) {
   ....
}