2016-09-29 122 views
0

我有一個列表功能,允許用戶將特定文章添加到個性化列表中。如果我將更多的文章添加到同一個列表中。該列表將在下拉菜單中複製。Laravel:在foreach語句中重複條目

例子:

enter image description here

相應的文章我將添加到具體名單。所以它重複。

數據庫表

list   | id | person_id | name  | description 
       | 1 15   | Test List | null 

data_list_ref | id | list_id | data_uid 
       | 1 | 1   | 9b888e1e9e 
       | 2 | 1   | jZ-mAtgh 

查詢

$lists = DB::table('list') 
    ->leftJoin('data_ref_list', 'data_ref_list.list_id', '=', 'list.id') 
    ->select('list.id', 'list.name', 'data_ref_list.data_uid') 
    ->where('person_id', Auth::user()->person_id) 
    ->get(); 

刀片實現

$ record->關鍵是目前的 '文章'

@foreach($lists as $list) 
    @if($list->data_uid === $record->key) 
    // show the checked list 
    // user's cant add the same article twice to a specific list 
    @else 
    // show the user's other lists 
    @endif 
@endforeach 
+0

dd(列表)產生了什麼? – zloter

+0

@zloter它產生2個項目相同的列表 –

+0

@WesMurray你可以請添加 - > groupBy('list.id')並再試一次。 –

回答

-1

嘗試使用口才在瀏覽器中被查看:關係。

創建2個模型https://laravel.com/docs/5.3/eloquent#defining-models 一個用於「list」,一個用於data_list_ref。

在模型「列表」創建「data_list_ref」 https://laravel.com/docs/5.3/eloquent-relationships#defining-relationships

包括模型在控制器這樣

use App\List; 

現在,如果你想從「列表」中獲取數據的關係,也是從「data_list_ref」你這樣稱呼它

$list = List::where('person_id', Auth::user()->person_id)->get(); 

獲取數據這是laravel的方式。