在一个模型或一个查询上使用2个查询,并使其成为toarray方法以获取其他查询

时间:2015-01-08 16:11:04

标签: php mysql laravel

我需要为选择输入获取一个关联数组,就像下面的代码一样。

public function create() {

  // queries the clients db table, orders by client_name and lists client_name and id
  $client_optons = DB::table('clients')->orderBy('client_name', 'asc')->lists('client_name','id');

    return View::make('projects.create', array('client_options' => $client_options));
}

但是我还需要获得整个模型$ clients。

public function create() {

   $clients=Clients::all();

   // queries the clients db table, orders by client_name and lists client_name and id
   $client_optons = DB::table('clients')->orderBy('client_name', 'asc')->lists('client_name','id');

    return View::make('projects.create', array('client_options' => $client_options));
}

由于我已经在查询中获取了整个模型,我的问题是我应该使用上面显示的2个查询还是性能/编码不好?我应该使用1个查询,然后使用模型来获取$ client选项吗? (如下图所示)我是通过循环执行此操作还是使用更简洁的数组函数?

public function create() {

  $clients=Clients::all();
  $clients_array = $clients->toArray();
  $client_options = /*some code to create array('client_name'=>'id') */


    return View::make('projects.create', array('client_options' => $client_options));
}

1 个答案:

答案 0 :(得分:1)

幸运的是,lists()函数也可用于集合:

$clients = Clients::orderBy('client_name', 'asc')->get();
$client_options = $clients->lists('client_name', 'id');

return View::make('projects.create', array(
    'client_options' => $client_options,
    'clients' => $clients
));