Laravel-Foreach循环-显示关于结果类型的特定消息 [英] Laravel - Foreach loop - Show a specific message for types of result
问题描述
所以我有一个包含所有消息的消息表.我希望固定的消息位于顶部,而普通消息则紧随其后.我可以使用查询中的orderBy()
方法正常执行此操作.
So I have a messages table with all messages. I want pinned messages to be at top and normal ones to follow after. I have been able to do this normally with the orderBy()
method in my query.
但是,我想为所有固定消息显示一些特定的消息.我想在固定消息的顶部有一个标头,在普通消息的顶部有一个标头,以使用户知道固定消息和普通消息在那里.
However, I want to display some specific messages for all my pinned messages. I would like to have a header at the top of the pinned messages and a header at the top of the normal messages to let users know that pinned and normal messages are there.
示例:
我的查询:
$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
我在数据库的列中有一些带有固定"的消息.因此,我希望固定的内容在"DESCRIPTIONS"的顶部显示.像这样:
I have a few messages with "pinned" in the column in database. So I want the pinned ones to show at the top WITH DESCRIPTIONS. Something like this:
Pinned
----------
Message text 3
----------
Normal
----------
Message text 1
Message text 2
我已经尝试过orderBy()
,并且在将其从固定到普通的顺序上都可以正常工作,但是我无法显示固定"和普通"消息.我该怎么办?
I have tried orderBy()
and it's working pretty good, in terms of ordering it from pinned to normal, but I can't get it to show the "Pinned" and "Normal" message. How can I do this?
推荐答案
尝试类似的方法(将1/0
更改为true/false
或您使用的任何方法):
Try something like this (change 1/0
to true/false
or whatever you use):
在控制器中:
$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
以避免代码重复.
If real @foreach
part is big, use partial and @each
instead of @foreach
to avoid code duplication.
替代
@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
替代方案
不太可读,但是如果您只需要短代码,请使用以下代码:
Not very readable, but if you just need short code, use something like this:
@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
这篇关于Laravel-Foreach循环-显示关于结果类型的特定消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!