download1323 2016-03-08 09:39
浏览 24

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

I am building a forum. I want to bring published topics on top whenever users leave a reply. For topics without replies, I want to order them by created_at column.

How do you do that?

Forum controller

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

Here is my topic table

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();
    });

Here is my comment table

$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();

Comments model

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');
    }

}

Topic model

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');
    }

}

still trying to figure this out. any help will be hugely appreciated!!

  • 写回答

2条回答 默认 最新

  • dsjojts9734 2016-03-08 11:06
    关注

    Try using eager load with constraint:

    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'));
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等