Php 作为数组键的Laravel雄辩ID
在我的控制器类中,我将获取所有属于当前登录用户的餐厅特色菜,以及特色菜的烹饪类型以及特色菜所属的餐厅 我使用以下代码段:Php 作为数组键的Laravel雄辩ID,php,laravel,eloquent,many-to-many,relationship,Php,Laravel,Eloquent,Many To Many,Relationship,在我的控制器类中,我将获取所有属于当前登录用户的餐厅特色菜,以及特色菜的烹饪类型以及特色菜所属的餐厅 我使用以下代码段: public function edit(Special $special) { dd($special->with('restaurants')->with('cuisines')->get()->keyBy('id')->toArray()); } 这将产生: ->keyBy('id')方法允许我将“特殊”数组键设置为数据库中的记录
public function edit(Special $special)
{
dd($special->with('restaurants')->with('cuisines')->get()->keyBy('id')->toArray());
}
这将产生:
->keyBy('id')方法允许我将“特殊”数组键设置为数据库中的记录id
但是,我不知道如何将关系记录数组键设置为它们各自的ID
例如。
餐厅数组中的第一项应具有键“1”。菜系数组中的第一项应具有“25”键
我试过这样的方法:
$special->with('restaurants')->keyBy('id')->with('cuisines')->keyBy('id')->get()->keyBy('id')->toArray()
它抛出:
方法照亮\Database\Query\Builder::keyBy不存在。
“我的菜系”和“餐厅”表都有一个主键id列。这应该可以做到:
$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;
});
使用以下命令:
$special->with($relations = ['restaurants', 'cuisines'])->get()->keyBy('id')
->each(function($special) use($relations) {
foreach($relations as $relation) {
$special->setRelation($relation, $special->$relation->keyBy('id'));
}
});
是收集功能,因此您需要“链接”此调用在您的每个关系上。我不打算在这里写整条链,但想法是
$special->with(['restaurants',cuisines'])->get()->keyBy('id')->first()->restaurants->keyBy('id')
。。。关键的一点是,这只适用于第一个$special
,所以您需要使用or。您能就答案给出反馈吗?@kyslik差不多了。是的,我在:)您需要返回$item
$special->with($relations = ['restaurants', 'cuisines'])->get()->keyBy('id')
->each(function($special) use($relations) {
foreach($relations as $relation) {
$special->setRelation($relation, $special->$relation->keyBy('id'));
}
});