Laravel orderBy 关系

新手上路,请多包涵

我正在遍历特定帖子的作者发布的所有评论。

 foreach($post->user->comments as $comment)
{
    echo "<li>" . $comment->title . " (" . $comment->post->id . ")</li>";
}

这给了我

I love this post (3)
This is a comment (5)
This is the second Comment (3)

我将如何按 post_id 排序,以便将上述列表排序为 3、3、5

原文由 PrestonDocks 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 356
1 个回答

可以使用查询函数扩展关系:

 <?php
public function comments()
{
    return $this->hasMany('Comment')->orderBy('column');
}

[评论后编辑]

 <?php
class User
{
    public function comments()
    {
        return $this->hasMany('Comment');
    }
}

class Controller
{
    public function index()
    {
        $column = Input::get('orderBy', 'defaultColumn');
        $comments = User::find(1)->comments()->orderBy($column)->get();

        // use $comments in the template
    }
}

默认用户模型 + 简单控制器示例;获取评论列表时,只需根据 Input::get() 应用 orderBy()。 (一定要进行一些输入检查;))

原文由 Rob Gordijn 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题