[英]How do I traverse through model relationships in laravel with dot syntax
I'm trying to traverse through complex eloquent model relationships/attributes, and I'd like to use a simple dot structure to iterate through this, similar to how you can traverse arrays with Arr::get()
我试图遍历复杂的雄辩模型关系/属性,我想使用一个简单的点结构来迭代这个,类似于你如何使用Arr::get()
遍历数组
Example: 例:
$data = [
'foo' => [
'bar' => [
'key' => 'value'
]
]
];
$value = Arr::get($data, 'foo.bar.key'); // returns 'value'
I've tried using 我试过用了
$value = Arr::get($model, 'relation.subrelation.attribute')
However this fails and aways returns null, even though eloquent models support ArrayAccess. 然而,即使雄辩的模型支持ArrayAccess,这也会失败并且aways返回null。
Does laravel have a simple way to accomplish this? laravel有一个简单的方法来实现这个目标吗?
For all those wondering, I've managed to figure out a solution by modifying the arr::pull() function to work specifically with models: 对于所有想知道的人,我设法通过修改arr :: pull()函数来专门用于模型来找出解决方案:
public static function traverse($model, $key, $default = null)
{
if (is_array($model)) {
return Arr::get($model, $key, $default);
}
if (is_null($key)) {
return $model;
}
if (isset($model[$key])) {
return $model[$key];
}
foreach (explode('.', $key) as $segment) {
try {
$model = $model->$segment;
} catch (\Exception $e) {
return value($default);
}
}
return $model;
}
Eloquent Models return a Collection
which is not the same as Array in PHP. Eloquent Models返回一个Collection
,它与PHP中的Array不同。 You can convert it to array using toArray()
function 您可以使用toArray()
函数将其转换为数组
$my_model->toArray();
This then gives you an Array. 然后,它会为您提供一个数组。 But remember that it converts all nested models inside the main model into an array as well. 但请记住,它还将主模型中的所有嵌套模型转换为数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.