Php 确定Laravel雄辩关系是否返回一个或多个
给定以下代码Php 确定Laravel雄辩关系是否返回一个或多个,php,api,laravel,relationship,eloquent,Php,Api,Laravel,Relationship,Eloquent,给定以下代码 class Post extends Eloquent { public function comments() { return $this->hasMany('Comment'); } public function author() { return $this->belongsTo('User'); } } 对/api/posts?embed=comments,author的请求
class Post extends Eloquent
{
public function comments()
{
return $this->hasMany('Comment');
}
public function author()
{
return $this->belongsTo('User');
}
}
对/api/posts?embed=comments,author
的请求应返回包含相关注释的所有帖子以及嵌入/嵌套在响应中的帖子作者
我可以使用$related=$post->getRelation($relation\u name)
获取相关项,但检查这是否返回集合或单个雄辩模型的最佳方法是什么
检查返回的类型似乎最简单(
$related instanceof Collection
),但我理解这是一种不好的做法。我是否遗漏了什么,或者不应该简单地使用$related->count()来解决这个问题?@Genie count()对我没有帮助,因为(1)在关系返回单个雄辩模型的情况下,它并不总是一个定义的方法,(2)找到的记录的实际数量并不重要,重要的是关系的类型是否是*-对一
或*-对多
。使用$post->comments,您将得到一个Collection@marcanuy,是的,但这不是问题所在(如果不清楚,请道歉)。我正在构建一个API,并试图以一种通用的方式实现嵌套关系。我将后类定义作为一个示例—实际上,我正在使用$model
和$relationship\u name
变量。我所知道的是$model
是一个雄辩的子类,$relationship\u name
是f定义关系的方法(示例中为注释
或作者
)。