2017-09-14 27 views
0

我有一個查詢Laravel 5.3中的問題。我有表Laravel數據庫查詢 - 選擇裏面的foreach

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有一些optimalization並傳遞$join功能的選擇只有一次,在最後一次迭代(第二它在我看來,我得到了2個標籤在請求)

回答

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是怎麼一回事,但我把它的值從上面的代碼,它應該只是罰款:)和我已經準備好調整爲你,如果你想

+0

這將整理標籤,不參加者我想,我是不是正確的?我想通過一些標籤與會者 – user3216673

+0

請不要掛機,我調整它排序:) –

+0

@ user3216673請檢查一遍,我改變了它,我測試了它在當地,希望它會爲你工作,以及:) –