Laravel将最后一个元素移到第一位

时间:2015-08-07 08:31:27

标签: laravel foreach

我正在尝试在laravel 5中构建简单的CMS。这是我的问题:

enter image description here

我不想移动那个测试|新主题第一页,第一个值。因为我在PhpMyAdmin中有is_new_topic行。所以我不想检查帖子是is_new_topic == 1然后将其移动到第一个foreach值。

viewTopic控制器:

<?php 

namespace App\Http\Controllers;
use DB;
use View;

class viewTopic extends Controller 
{
    public function showTopic($tname, $tid)
    {
        $topics  = DB::table('topics')
                    ->where('id', $tid)
                    ->where('seo_title', $tname)
                    ->first();

        $posts  = DB::table('posts')
                    ->where('topic_id', $tid)
                    ->join('users', 'users.id', '=', 'posts.author_id')
                    ->select()
                    ->paginate(3);

        return View::make('posts', compact('topics', 'posts'));
    }
}

路线:

Route::get('topic/{tname}/{tid}', 'viewTopic@showTopic');

模板:

@extends('layouts.main')
@section('breadcrumb')
<ol class="breadcrumb">
  <li class="active" data-toggle="tooltip" data-placement="right" title="{{ $topics->title }}">{{ $topics->title }}</li>
</ol>
@stop
@section('content')
<div class="media">
  <div class="media-body" rel="#author{{ $topics->author_id }}">
  </div>
    @foreach($posts as $post)
    <div class="media">
  <div class="media-left">
    <a href="{{ generateProfileURL(str_slug($post->name), $post->id) }}">
      <img class="media-object" src="http://localhost/uploads/avatars/{{ $post->avatar_id }}.{{ $post->avatar_end }}" style="width: 64px">
    </a>
  </div>
  <div class="media-body" rel="#post{{ $post->pid }}">
  <a href="{{ generateProfileURL($post->name, $post->id) }}">{{ $post->name }}</a><br>{{ $post->text }}
  @if (Auth::check())
  @if($post->id == Auth::user()->id)
  <br><a href="#">Edit</a>
  @endif
  @endif
  </div>
</div>
@endforeach
</div>
{!! $posts->render() !!}
@stop

提前致谢:)

1 个答案:

答案 0 :(得分:2)

我假设is_new_topic列中的值对于新值为1,对于旧值为0。您必须按照以下代码中的desc列进行排序:

$posts  = DB::table('posts')
                    ->where('topic_id', $tid)
                    ->join('users', 'users.id', '=', 'posts.author_id')
                    ->orderBy('is_new_topic', 'desc');
                    ->select()
                    ->paginate(3);
相关问题