在eloquent中使用keyBy方法和方法

时间:2014-10-22 08:50:46

标签: laravel-4 eloquent

我想在Eloquent中使用带有方法的keyBy方法。像这样:

$settings = $settings->with(
    array('languages' => function($query)
    {
        $query->get()->keyBy('languages_language_id');
    })
)->get()->keyBy('setting_key');

我该怎么做?感谢。

2 个答案:

答案 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;
    }
}