我使用三个表备件,类别和参数以及Yajra Datatables。
我的控制器动作是:
public function anyData()
{
$spareparts_param_list = Sparepart::all();
$list='';
foreach ($spareparts_param_list as $value) {
foreach ($value->category->parameter as $par_list) {
$list .= $par_list->Name.',';
}
}
$spareparts = Sparepart::
join('cars', 'spareparts.car_id', '=', 'cars.id')
->select(['spareparts.id', 'cars.Brend', 'spareparts.Model', $list]);
$datatables = app('datatables')->of($spareparts);
return $datatables->make();
}
我的数组列表$ list打印参数,如颜色,类型,轮胎等。如何在select查询中传递$ list数组?
你可以使用whereIn(),如下所示:
$users = DB::table('users')
->whereIn('id', [1, 2, 3])
->get();
你可以使用whereIn
:
public function anyData()
{
$spareparts_param_list = Sparepart::all();
$list = [];
foreach ($spareparts_param_list as $value) {
foreach ($value->category->parameter as $par_list) {
$list[] = $par_list->Name;
}
}
$spareparts = Sparepart::
join('cars', 'spareparts.car_id', '=', 'cars.id')
->whereIn('Name', $list)
->select(['spareparts.id', 'cars.Brend', 'spareparts.Model']);
$datatables = app('datatables')->of($spareparts);
return $datatables->make();
}
你可以运行这个原始的Mysql
命令:
select sp.id as sp_id, sp.model as sp_model, c.brend as car_brend, json_arrayagg(p.name) as p_name
from spareparts as sp
join cars as c on sp.car_id=c.id
join categories as cat on sp.category_id=cat.id
join parameters as p on cat.id=p.category_id
group by sp.model;
上面的命令会给你一个如下结果:
1 | Audi A6 door | Audi A6 | ["color", "window"]
最后一列将是与每个类别相关的所有参数的json列。