Ad

Laravel Pass List Parameters (columns) In Select Query

I use three table spareparts, categories and parameter and YajraDatatables.

My controller action is:

    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();
    }

My array list $list print parameters such as color,type,tires,. How to pass $list array in select query?

Ad

Answer

You can use 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();
}

You can run this raw Mysql command:

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;

Above command will give you a result like the following:

1 | Audi A6 door | Audi A6 | ["color", "window"]

The last column will be a json column of all parameters related to each category.

Ad
source: stackoverflow.com
Ad