在 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; // nullcount($model->relation); // 0 evaluates to false// there is one$model->relation; // Eloquent Modelcount($model->relation); // 1 evaluates to true
一对多关系:
hasMany/
belongsToMany/
morphMany/
morphToMany/
morphedByMany
// no related collection$model->relation; // Collection with 0 items evaluates to truecount($model->relation); // 0 evaluates to false// there are related models$model->relation; // Collection with 1 or more items, evaluates to true as wellcount($model->relation); // int > 0 that evaluates to true



