拉拉维尔获取嵌套关系值


Laravel get nested relation value

是否存在在 Laravel 5 中轻松获取关系值的可能性?这是我需要的示例:

我有模型Book,我与模型Authorauthor关系。 Author也与模型Country有关系country。我需要在书页上显示作者的国家名称。我可以很容易地写道:

echo $model->author->country->name

但是,如果没有提供书籍的作者或我们不知道作者的形象怎么办?我会得到通知。

所以我需要添加额外的检查:

if ($model->author && $model->author->country) echo $model->author->country->name

也许 laravel 中存在某种方法,可以简化获取值的过程?也许像SomeHelperClass::getValue($model, 'author.country.name')这样的东西,所以如果链的某个部分null,那么方法也返回null。谢谢。

很抱歉回答我自己的问题。无论如何:

Laravel 5.1 有辅助功能array_get,其工作原理与我想要的类似。但问题是函数仅适用于数组。所以我需要急切加载所有必需的数据并将对象转换为数组:

$model = Book::with('author.country')->findOrFail($id);
$country_name = array_get($model->toArray(), 'author.country.name');
// or
$country_name = object_get($model, 'author.country.name');