mardi 5 mai 2020

Laravel - Query an array of fields - How to generate query

I'm struggeling with building a query in laravel. I have, depending on the table, zero, one or several fields I want to check for the value holzId. This is the section where the table and the fields to query are set:

switch($modul->id) {    
    ...
    case 12:
        $nachweisTable = 'tbl_a';
        $fields = ["fieldA"];
        break;
    case 13:
        $nachweisTable = 'tbl_b';
        $fields = ["someOtherFieldA","fieldB","someDifferentField"];
        break;
    case 15:
        $nachweisTable = 'tbl_c';
        $fields = [];
        break;
    ...
}

Now I need to integrate something like a for loop or similar to query all fields given in the array:

return $this->model
    ->query()
    ->join('tbl_nachweis', function($join){
        $join->on('tbl_projekt_positionen.id', '=', 'tbl_nachweis.projekt_position_fk')
            ->on('tbl_projekt_positionen.modul_fk', '=', 'tbl_nachweis.modul_fk');
    })
    ->join($nachweisTable,'tbl_nachweis.nachweis_daten_fk','=',$nachweisTable .'.id')
    ->where('tbl_projekt_positionen.projekt_fk', $projektId)
    ->where('tbl_projekt_positionen.modul_fk', $modulId)
    // --> here I need to implement something like a for loop or something similar
    // to check the value $holzId in the given array for each value combined with an `or`
    ->orderBy('nummer')
    ->orderBy('bezeichnung')
    ->get();

In an example for case 13, I need the following result:

return $this->model
    ->query()
    ...
    ->where($nachweisTable .'.someOtherFieldA', '=', $holzId)
    ->orWhere($nachweisTable .'.fieldB', '=',$holzId)
    ->orWhere($nachweisTable .'.someDifferentField', '=',$holzId)
    ...

In case of case 12 I only want to query one field:

return $this->model
    ->query()
    ...
    ->where($nachweisTable .'.fieldA', '=', $holzId)
    ...

Has anyone a hint for me, how can I achieve this in laravel with the query builder? Many thanks in advance!



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire