因为一个案例,我需要将多个表的 Eloquent 查询存储到一个数组中,并将它们传递给 View ,然后在 View 中我应该处理它们。那么我该怎么做,我已经尝试使用 call_user_func()
和 call_user_func_array()
机器人没有解决问题并且无法运行。下面是我的 Eloquent 数组。
$my_eloquent_array = array('course' => 'App\Models\Course::all();',
'user' => 'App\Models\User::whereHas(
\'roles\', function($q){
$q->where(\'name\',\'course_coordinator\');
}
)->get(array(\'id\',DB::raw(\'CONCAT(first_name, " ", last_name) AS full_name\')))'
);
那么现在在一个循环内查看我如何运行那些 Eloquent 数组值?
$resourceDropdowns = array(
'curriculum_id' => array('query' => 'App\Models\ProfessionalDevelopment\Curriculum::all(\'id\',\'name\')', 'label' => 'Curriculum'),
'classroom_id' => array('query' => 'Classroom::all(\'id\',\'no\')', 'label' => 'Classroom'),
'training_coordinator_id' => array('query' => 'User::whereHas(
\'roles\', function($q){
$q->where(\'name\',\'course_coordinator\');
}
)->get(array(\'id\',DB::raw(\'CONCAT(first_name, " ", last_name) AS full_name\')))', 'label' => 'Training Coordinator'),
'focal_point_id' => array('query' => 'User::whereHas(
\'roles\', function($q){
$q->where(\'name\',\'focal_point\');
}
)->get(array(\'id\',DB::raw(\'CONCAT(first_name, " ", last_name) AS full_name\')))', 'label' => 'Focal Point'),
'master_trainer_id' => array('query' => 'User::whereHas(
\'roles\', function($q){
$q->where(\'name\',\'master_trainer\');
}
)->get(array(\'id\',DB::raw(\'CONCAT(first_name, " ", last_name) AS full_name\')))', 'label' => 'Master Trainer'),
'stage_id' => array('query' => 'Stage::all(\'id\',\'no\')', 'label' => 'Stage'),
'stream_id' => array('query' => 'Stream::all(\'id\',\'no\')', 'label' => 'Stream'),
'unit_id' => array('query' => 'Unit::all(\'id\',\'no\')', 'label' => 'Unit'),
);;
if(count($resourceDropdowns) > 0){
$dropDownFilters = array();
foreach($resourceDropdowns as $drop_key => $drop_val){
$dropDownFilters[$drop_key]['query'] = $drop_val['query'];
$dropDownFilters[$drop_key]['label'] = $drop_val['label'];
}
}
但是 $drop_val['query']
没有运行,它只是最终数组中的一个字符串。
最佳答案
我不确定这是否有效,但您可以尝试一下。我会尝试存储函数并在遍历它们时执行它:
// We store the queries with its associated parameters
$queries = [ ["query" => App\Models\Course::all, "params" => null ]];
// We loop over the functions to be executed
foreach($queries as $query){
// Now, we execute the function
$query["query"]($query["params"])->get();
}
我不确定这个例子是否有效,但我会推荐你这样的方法。
您必须考虑将复杂参数传递给函数的良好解决方案。
关于php - Laravel 如何运行作为数组值并传递给 View 的 Eloquent 查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34758791/