Laravel数据库查询 - 在foreach中选择

时间:2017-09-14 12:22:55

标签: laravel laravel-5 eloquent

我在Laravel 5.3中遇到了查询问题。我有桌子

attendees->attendee_tag<-tags(M:N关系)

我希望让参与者按多个标签排序,所以我写了这个:

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

但是我得到了以下sql错误:

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)

看起来,laravel有一些优化并且只在$join函数上传递一次,在最后一次迭代中(在我看来,第二次迭代,我在请求中得到了2个标签)

1 个答案:

答案 0 :(得分:0)

我假设您在参加者模型中有tags()关系!

我测试过它并且工作正常

$attendees = Attendee::join('attendee_tag', 'attendee_tag.attendee_id', '=', 'attendees.id')
                         ->join('tags', 'attendee_tag.tag_id', '=', 'tags.id')->where('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;
        $attendees->orderBy('tags.' . $sort_value, $column['order']);
        $i++;
    }
    $attendees->get();
PS:我不知道$order_by的全部内容,但我从上面的代码中获取了它的价值,它应该可以正常工作:)我准备调整它如果你想要的话