Laravel 在 select 查询中传递列表参数(列)

Laravel pass list parameters (columns) in select query

我使用三个table备件类别参数和YajraData table秒。

我的控制器操作是:

    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 打印参数,例如 color,type,tires,。 如何在 select 查询中传递 $list 数组?

您可以使用 whereIn(),像这样:

$users = DB::table('users')
                ->whereIn('id', [1, 2, 3])
                ->get();

文档 - https://laravel.com/docs/5.7/queries#where-clauses

您可以使用 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 列。