2016-04-22 38 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'刀片语法。谢谢! –