在论坛索引页面上将最新评论的主题放在首位

时间:2016-03-08 09:39:09

标签: php laravel eloquent

我正在建立一个论坛。我想在用户发表回复时将发布的主题放在首位。对于没有回复的主题,我想按created_at列排序。

你是怎么做到的?

论坛控制器

public function index()
{
    $categories = Category::all();
  $topics = Topic::with(['comments' => function ($query) {
  $query->orderBy('comments.created_at', 'desc');
  }])->paginate(20);
}

这是我的主题表

Schema::create('topics', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('category_id')->unsigned();
        $table->integer('user_id')->unsigned();

        $table->string('title');
        $table->text('body');
        $table->timestamps();
    });

这是我的评论表

$table->increments('id');
        $table->text('reply');
        $table->integer('user_id')->unsigned();


        $table->integer('topic_id')->unsigned();
        $table->foreign('topic_id')->refrenced('id')->on('topics')->onDelete('cascade');

        $table->timestamps();

评论模型

class Comment extends Model
{
    protected $fillable = [
        'reply',
        'user_id',
        'topic_id'
    ];


    public function topic()
    {
        return $this->belongsTo('App\Topic');
    }

    public function user()
    {
        return $this->belongsTo('App\User');
    }

}

主题模型

class topic extends Model
{
   protected $fillable = [
       'title',
       'body',
       'category_id'
    ];

    public function category()
    {
        return $this->belongsTo('App\category');
    }

    public function user()
    {
        return $this->belongsTo('App\User');
    }

    public function comments()
    {
        return $this->hasMany('App\Comment');
    }

}

仍在努力解决这个问题。任何帮助将非常感谢!!

2 个答案:

答案 0 :(得分:1)

尝试使用带约束的预先加载:

public function index()
{
    $categories = Category::all();
    $topics = Topic::with(['comments' => function ($query) {
        $query->orderBy('created_at', 'desc');
    }])->paginate(20);

    return view('forums.index',compact('categories','topics'));
}

答案 1 :(得分:0)

(5, 3)