3 回答
![?](http://img1.sycdn.imooc.com/54584de700017cbd02200220-100-100.jpg)
TA贡献1893条经验 获得超10个赞
在php 7.2+中,您不能count在关系对象上使用,因此对于所有关系都没有一种万能的方法。使用查询方法代替@tremby,如下所示:
$model->relation()->exists()
适用于所有关系类型的通用解决方案(php 7.2之前的版本):
if (count($model->relation))
{
// exists
}
由于动态属性返回Model或,因此这将适用于每个关系Collection。两者都实现ArrayAccess。
所以它是这样的:
单一的关系: hasOne / belongsTo/ morphTo/morphOne
// no related model
$model->relation; // null
count($model->relation); // 0 evaluates to false
// there is one
$model->relation; // Eloquent Model
count($model->relation); // 1 evaluates to true
一对多关系: hasMany / belongsToMany/ morphMany/ morphToMany/morphedByMany
// no related collection
$model->relation; // Collection with 0 items evaluates to true
count($model->relation); // 0 evaluates to false
// there are related models
$model->relation; // Collection with 1 or more items, evaluates to true as well
count($model->relation); // int > 0 that evaluates to true
![?](http://img1.sycdn.imooc.com/545863b500014e4602200220-100-100.jpg)
TA贡献1995条经验 获得超2个赞
甲Relation对象穿过一个未知的方法调用口才查询生成器,其被设置为仅选择相关对象。该Builder进而将未知方法调用传递到其基础查询Builder。
这意味着您可以直接从关系对象使用exists()or count()方法:
$model->relation()->exists(); // bool: true if there is at least one row
$model->relation()->count(); // int: number of related rows
注意relation:后面的括号->relation()是一个函数调用(获取关系对象),->relation与之相反,Laravel为您设置了一个魔术属性获取器(获取相关对象)。
count在关系对象上使用方法(即使用括号)将比这样做$model->relation->count()或count($model->relation)(除非该关系已被急切加载)要快得多,因为它运行计数查询而不是为任何相关对象提取所有数据从数据库中,只是为了计算它们。同样,使用exists也不需要提取模型数据。
无论exists()和count()工作在我已经尝试了所有关系类型,所以至少belongsTo,hasOne,hasMany,和belongsToMany。
![?](http://img1.sycdn.imooc.com/5458477300014deb02200220-100-100.jpg)
TA贡献1846条经验 获得超7个赞
之后的PHP 7.1,接受的答案将不是对所有类型的关系的工作。
因为根据类型的关系,Eloquent将返回a Collection,a Model或Null。并且在PHP 7.1 count(null)中将抛出一个error。
因此,要检查该关系是否存在,可以使用:
对于单一关系:例如hasOne和belongsTo
if(!is_null($model->relation)) {
....
}
对于多重关系:例如:hasMany和belongsToMany
if ($model->relation->isNotEmpty()) {
....
}
- 3 回答
- 0 关注
- 942 浏览
添加回答
举报