Laravel Eloquent ID作为数组键

时间:2018-05-11 06:17:40

标签: php laravel eloquent many-to-many relationship

在我的控制器课程中,我将获取属于当前登录用户的所有餐厅特色菜,以及特殊菜肴的菜肴类型以及特殊菜肴所属的餐厅。

我使用以下代码段:

public function edit(Special $special)
{
   dd($special->with('restaurants')->with('cuisines')->get()->keyBy('id')->toArray());
}

这会产生:

enter image description here

- > keyBy('id')方法允许我将“特殊”数组键设置为数据库中的记录ID。

但是,我无法弄清楚如何将关系记录数组键设置为各自的ID。

例如。 restaurants数组中的第一项应该有一个键“1”。 cuisines数组中的第一项应该有一个“25”的键。

我尝试过这样的事情:

$special->with('restaurants')->keyBy('id')->with('cuisines')->keyBy('id')->get()->keyBy('id')->toArray()

抛出: 方法Illuminate \ Database \ Query \ Builder :: keyBy不存在。

我的菜肴和餐馆餐桌都有一个主键ID列。

3 个答案:

答案 0 :(得分:0)

这应该可以解决问题:

$result = $special->with(['restaurants', 'cuisines'])->get()->keyBy('id')->map(function ($item) {
    $item->restaurants->keyBy('id');
    $item->cuisines->keyBy('id');

    return $item;
});

或稍好一点的版本:

$result = $special->with(['restaurants', 'cuisines'])->get()->keyBy('id')->map(function ($item) {
    foreach (array_keys($item->getRelations()) as $relation) {
        if ($item->relationLoaded($relation)) {
            $item->$relation->keyBy('id');
        }
    }

    return $item;
});

答案 1 :(得分:0)

使用此:

$special->with($relations = ['restaurants', 'cuisines'])->get()->keyBy('id')
    ->each(function($special) use($relations) {
        foreach($relations as $relation) {
            $special->setRelation($relation, $special->$relation->keyBy('id'));        
        }
    });

答案 2 :(得分:-1)

 $result = $special->with(['restaurants', 'cuisines'])->get()
        ->keyBy('id')
        ->map(function ($item) {
        $item->restaurants->keyBy('id');
        $item->cuisines->keyBy('id');
        return $item;
    });