将最新评论的主题放在论坛索引页面的顶部


Bring the latest commented topic on top on forum index page

我正在建立一个论坛。每当用户留下回复时,我想将已发布的主题放在首位。对于没有回复的主题,我想按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');
    }
}

仍在努力解决这个问题。 任何帮助将不胜感激!

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

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'));
}
DB::table('topics')
->leftjoin('comments', function($join) {
                    $join->on('topics.id', '=', 'comments.topic_id');
                })
->select(DB::raw('IF(comments.id IS NULL,0, 1) as topic_comment'))
->orderBy('topic_comment', 'DESC')
->orderBy('topics.created_at', 'DESC')
->get();
the topic_comment as 1 records you can show on top right and rest wherever you want