2016-04-08 141 views
0

我能得到这个使用选择的工作:Laravel 5.2雄辩使用加载查询

User::whereNotIn('id', $ids) 
    ->select(['id', 'email']) 
    ->with('profile') 
    ->get(); 

我想只检索是即时加载用户配置文件一对夫妇键。我想要做这样的事情:

User::whereNotIn('id', $ids) 
    ->select(['id', 'email']) 
    ->with(['profile', function ($query) { 
     $query->select(['id', 'user_id', 'first_name', 'last_name']); 
    }])->get(); 

或者:

User::whereNotIn('id', $ids) 
    ->select(['id', 'email']) 
    ->with(['profile', function ($query) { 
     $query->addSelect(['id', 'user_id', 'first_name', 'last_name']); 
    }])->get(); 

但是,这似乎并没有工作,我得到这个错误:

ErrorException in Builder.php line 1034: 
explode() expects parameter 2 to be string, object given 

抛出/Illuminate/Database/Eloquent/Builder.php:

/** 
* Parse the nested relationships in a relation. 
* 
* @param string $name 
* @param array $results 
* @return array 
*/ 
protected function parseNestedWith($name, $results) 
{ 
    $progress = []; 

    // If the relation has already been set on the result array, we will not set it 
    // again, since that would override any constraints that were already placed 
    // on the relationships. We will only set the ones that are not specified. 
    foreach (explode('.', $name) as $segment) { // <--- line 1034 
     $progress[] = $segment; 

     if (! isset($results[$last = implode('.', $progress)])) { 
      $results[$last] = function() { 
       // 
      }; 
     } 
    } 

    return $results; 
} 

有没有办法做到这一点?

回答

1

使用“addSelect”而不是“选择”的渴望负荷约束封闭

User::whereNotIn('id', $ids)->select(['id', 'email']) 
    ->with(['profile' => function($query) { 
     $query->addSelect(['id', 'user_id', 'first_name', 'last_name']); 
    }])->get(); 

你必须包括对addSelect外键,否则什么也不会被加载

+0

嗨里面,我试过了,但我得到这个错误:'ErrorException在Builder.php行1034: explode()期望参数2是字符串,对象给予' – mtpultz

+1

更新,我没有注意到你正在使用数组符号进行急切加载 – naneri

+0

哦,挽救生命!我永远不会想到需要添加的外键列,我搞砸了数组符号。我错过了'=>'。 – mtpultz