在一个模型或 1 个查询上使用 2 个查询,并使其成为数组方法以获取其他查询
use 2 queries on one model or 1 query and make it toarray method to get other query
我需要为 select 输入获取关联数组,就像下面的代码一样。
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 个查询还是那不好 performance/coding?我应该使用 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));
}
幸运的是,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
));
我需要为 select 输入获取关联数组,就像下面的代码一样。
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 个查询还是那不好 performance/coding?我应该使用 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));
}
幸运的是,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
));