所以我有一个包含所有消息的消息表。我希望固定的消息位于顶部,而正常的消息紧随其后。我已经能够在查询中使用 orderBy()
方法正常执行此操作。
但是,我想为所有固定的邮件显示一些特定的消息。我希望在固定消息的顶部有一个标头,在正常消息的顶部有一个标头,以便让用户知道固定和正常消息在那里。
例:
我的查询:
$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
我在数据库的列中有一些"固定"的消息。所以我希望固定的那些显示在顶部和描述。像这样:
Pinned
----------
Message text 3
----------
Normal
----------
Message text 1
Message text 2
我已经尝试了orderBy()
并且它在从固定到正常排序方面工作得很好,但我无法让它显示"固定"和"正常"消息。我该怎么做?
尝试这样的事情(1/0
更改为true/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
部分很大,请使用部分和@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