2016-04-22 39 views
1

所以我有一個包含所有消息的消息表。我希望固定的消息在頂部和普通的消息之後。在我的查詢中,我可以通過orderBy()方法正常執行此操作。Laravel - Foreach循環 - 顯示特定消息的結果類型

但是,我想顯示所有固定消息的一些特定消息。我希望在固定消息的頂部有一個標題,在正常消息的頂部有一個標題,以便讓用戶知道固定消息和正常消息在那裏。

例子:

我的查詢:

$rows = Messages::where('active', true)->orderBy('pinned', 'desc')->get(); 

我的觀點

@foreach ($rows as $row) 
    {{ $row->message }} 
@endforeach 

我看到了什麼

Message text 3 
Message text 1 
Message text 2 

我有幾條消息與在 「固定」數據庫中的列。所以我想要固定的人在頂部顯示WITH DESCRIPTIONS。事情是這樣的:

Pinned 
---------- 
Message text 3 
---------- 
Normal 
---------- 
Message text 1 
Message text 2 

我試圖orderBy(),它的工作相當不錯,從固定到正常責令方面,但我不能得到它顯示的「固定」和「正常」的消息。我怎樣才能做到這一點?

+0

怎麼樣使用條件。 – aldrin27

+0

你可以print_r($ rows)嗎?' – aldrin27

回答

1

嘗試這樣的事情(變更1/0true/false或任何你使用):

在控制器:

$pinned = $rows->where('pinned', 1); 
$normal = $rows->where('pinned', 0); 

在視圖:

@if(count($pinned) > 0) 
    Pinned 

    @foreach ($pinned as $row) 
     {{ $row->message }} 
    @endforeach 
@endif 

@if(count($normal) > 0) 
    Normal 

    @foreach ($normal as $row) 
     {{ $row->message }} 
    @endforeach 
@endif 

如果真正@foreach部分大,用partial and @each而不是@foreach來避免代碼重複。

替代

@foreach ($rows as $row) 
    @if ($row->pinned === 1 && !isset($pinnedShown)) 
     Pinned 
     {{ $pinnedShown = true }} 
    @endif 

    @if ($row->pinned === 0 && !isset($normalShown)) 
     Normal 
     {{ $normalShown = true }} 
    @endif 

    {{ $row->message }} 
@endforeach 

短替代

不是很可讀,但如果你只需要很短的代碼,使用這樣的:

@foreach ($rows as $row) 
    <?php !($row->pinned == 1 && !isset($pin)) ? : $pin = call_user_func(function(){ echo 'Pinned'; return 1; }); 
      !($row->pinned == 0 && !isset($nor)) ? : $nor = call_user_func(function(){ echo 'Normal'; return 1; }); ?> 
    {{ $row->message }} 
@endforeach 
+0

對不起,沒有看到這個。我以第一種方式使用'@ each'刀片語法。謝謝! –