Php Laravel-Foreach循环-显示结果类型的特定消息

Php Laravel-Foreach循环-显示结果类型的特定消息,php,laravel,laravel-5.2,Php,Laravel,Laravel 5.2,所以我有一个包含所有消息的消息表。我希望被钉住的消息在顶部,正常的消息在后面。通过查询中的orderBy()方法,我可以正常地执行此操作 但是,我想为我的所有固定邮件显示一些特定的邮件。我希望在固定消息的顶部有一个标题,在普通消息的顶部有一个标题,以让用户知道固定消息和普通消息都在那里 例如: 我的问题是: $rows = Messages::where('active', true)->orderBy('pinned', 'desc')->get(); 我的看法 @foreach

所以我有一个包含所有消息的消息表。我希望被钉住的消息在顶部,正常的消息在后面。通过查询中的
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
我在数据库的列中有一些带有“pinted”的消息。因此,我希望在顶部显示钉住的,并附有说明。大概是这样的:

Pinned
----------
Message text 3
----------
Normal
----------
Message text 1
Message text 2
@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
我已经尝试了
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
如果real
@foreach
部分较大,请使用而不是
@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)
    @if ($row->pinned === 1 && !isset($pinnedShown))
        Pinned
        {{ $pinnedShown = true }}
    @endif

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

    {{ $row->message }}
@endforeach
可读性不强,但如果您只需要简短的代码,请使用以下代码:

Pinned
----------
Message text 3
----------
Normal
----------
Message text 1
Message text 2
@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
@foreach($rows作为$row)
{{$row->message}
@endforeach

使用条件如何。您能
打印($rows)吗?
对不起,没有看到这个。我使用了第一种方法,并使用了
@each
blade语法。非常感谢。