【问题标题】:Bring the latest commented topic on top on forum index page将最新评论的主题放在论坛索引页面的顶部
【发布时间】:2016-04-05 13:35:10
【问题描述】:

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

}

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

【问题讨论】:

    标签: php laravel eloquent


    【解决方案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'));
    }
    

    【讨论】:

    • 感谢您的回复。我已经尝试过了,并在我的第二个帖子中留下了回复,以查看主题是否在索引页面上排在第一位,但没有奏效。
    【解决方案2】:
    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-18
      • 2020-01-14
      • 2017-06-30
      • 1970-01-01
      • 2014-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多