因为一个案例,我需要将多个表的雄辩查询存储到一个数组中,并将它们传递给视图,然后在视图中处理它们。那么我该怎么做呢?我已经尝试过call_user_func()
和call_user_func_array()
机器人没有解决问题,无法运行。贝娄是我口若悬河的阵列。
$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'')))'
);
那么,现在在一个循环中查看如何运行那些雄辩的数组值?
$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();
}
我不确定这个例子是否有效,但我建议您使用这样的方法。
您必须考虑一个将复杂参数传递给函数的好解决方案。
您也可以通过这种方式编写相同的代码。
$cources = App'Models'Course::all();
$users = 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')));
$my_eloquent_array = array('course' => $cources,
'user' => $users
);
return view('VIEW_NAME', ['data' => $my_eloquent_array]);
用eval($drop_val['query'])
替换$drop_val['query']
注意:-使用eval()函数时,请始终在每个字符串的末尾加分号(;)。在你的情况下,你必须写
array('query'=>'App'Models'Course::all();');
如果此代码不起作用,请尝试以下方式:-
$arr = array('query'=>base64_encode(App'Models'Course::all()));
$user = base64_decode($arr['query']);