jeudi 14 septembre 2017

Laravel database query – select inside foreach

I've got a problem with a query in Laravel 5.3. I've got tables

attendees->attendee_tag<-tags (M:N relation)

and I would like to get attendees ordered by multiple tags, so I wrote this:

$query = Attendee::where('attendees.event_id', '=', $event_id);
$i = 1;
foreach($order_by as $column) {
    $tag = $this->tagService->findTagById($column['tag_id']);
    $sort_value = $tag->value_type == 'string' ? 'value_string_'.$i : 'value_int_'.$i;
    $query->join('attendee_tag as at_'.$i, function ($join) use ($tag, $i) {
        $join->on('attendees.id', '=', 'at_'.$i.'.attendee_id')
            ->where('at_'.$i.'.tag_id', '=', $tag->id);})
        ->select('at_'.$i.'.id as relationId_'.$i, 'at_'.$i.'.value_string as value_string_'.$i, 'at_'.$i.'.value_int as value_int_'.$i, 'attendees.id as id')
        ->orderBy($sort_value, $column['order']);
        $i++;
    }
$attendees = $query->get();

But I'm getting following sql error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'value_string_1' in 'order clause' (SQL: select `at_2`.`id` as `relationId_2`, `at_2`.`value_string` as `value_string_2`, `at_2`.`value_int` as `value_int_2`, `attendees`.`id` as `id` from `attendees` inner join `attendee_tag` as `at_1` on `attendees`.`id` = `at_1`.`attendee_id` and `at_1`.`tag_id` = 3 inner join `attendee_tag` as `at_2` on `attendees`.`id` = `at_2`.`attendee_id` and `at_2`.`tag_id` = 4 where `attendees`.`event_id` = 1 order by `value_string_1` asc, `value_string_2` asc limit 1000 offset 0)

It seems, that laravel has some optimalization and passes the select on $join function only once, in last iteration (second iteration in my opinion, I got 2 tags in request)



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire