我有这个:
$foo = Foo::getFooById(100);
public static function getFooById($id)
{
return Foo::where('id', $id)->with('locations')->firstOrFail();
}这将返回一个雄辩的集合。
$foo现在提供了以下属性:
$foo->name
$foo->locations$foo->locations是一个始终包含1个元素的数组
我只想:
$foo->location = $foo->locations[0];
unset($foo->locations);这段代码可以工作,但非常糟糕,因为它发生在不同的地方。我怎样才能清楚地做到这一点呢?
发布于 2015-07-30 18:15:24
您还没有展示它,但我假设您已经将Foo定义为与位置具有一对多关系。
如果任何给定的Foo总是只有一个位置,那么您应该使用一对一关系而不是一对多关系来定义它,那么您将能够使用$foo->location来获取单个位置对象,而不是使用$foo->locations来获取它们的数组。
换句话说,我猜你的Foo模型中有如下代码:
public function locations()
{
return $this->hasMany('locations');
}您需要将其替换为更像这样的内容:
public function location()
{
return $this->hasOne('locations');
}然后将查询函数中的with('locations')更改为with('location')。
https://stackoverflow.com/questions/31719517
复制相似问题