我想在Eloquent中使用带有方法的keyBy方法。像这样:
$settings = $settings->with(
array('languages' => function($query)
{
$query->get()->keyBy('languages_language_id');
})
)->get()->keyBy('setting_key');
我该怎么做?感谢。
答案 0 :(得分:1)
您不能直接在with
条款中执行此操作,而是可以使用keyBy
版本覆盖该集合:
foreach ($settings as $keySetting => $setting)
{
$settings[$keySettings]->languages = $settings[$keySettings]->languages->keyBy('languages_language_id');
}
如您所见,您仍然需要迭代结果并逐个重新排序。这只是使用keyBy
你正在做的事情的更简洁版本。
答案 1 :(得分:0)
最后我用这个:
$settings = $settings->with('languages')->get()->keyBy('setting_key')->toArray();
foreach ($settings as $keySetting => $setting)
{
$languages = $setting['languages'];
$settings[$keySetting]['languages'] = array();
foreach ($languages as $lang)
{
$settings[$keySetting]['languages'][$lang['languages_language_id']] = $lang;
}
}