首页 >后端开发 >php教程 >如何在 Laravel 中使用'orderBy”订购相关模型?

如何在 Laravel 中使用'orderBy”订购相关模型?

Mary-Kate Olsen
Mary-Kate Olsen原创
2024-11-29 06:11:10736浏览

How to Order Related Models in Laravel Using `orderBy`?

在 Laravel 中排序关系

检索一组相关模型时,以特定方式对它们进行排序通常很有用。在 Laravel 中,这可以使用 orderBy 方法来实现。

排序 HasMany 关系

考虑以下场景,其中您循环遍历特定帖子的作者发布的所有评论:

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

    此代码将显示以下列表comments:

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

    要按帖子 ID 对评论进行排序,请扩展 User 模型中的 hasMany 关系:

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

    将 column 替换为您要排序的列的名称。在本例中,我们将使用 id:

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

    这会将评论的顺序更新为:

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

    使用查询参数排序

    中除了对关系中的顺序进行硬编码之外,您还可以基于查询参数进行排序。为此,请在您的routes.php文件中定义一个路由:

    Route::get('users/{user}/comments', 'UserController@index');

    然后在您的UserController中创建相应的索引方法:

    public function index($user)
    {
        $column = Input::get('orderBy', 'defaultColumn');
        $comments = $user->comments()->orderBy($column)->get();
    
        // ...
    }

    当您使用orderBy参数,评论将相应地排序。例如,访问以下 URL 将按created_at 列对评论进行排序:

    http://localhost/users/1/comments?orderBy=created_at

    以上是如何在 Laravel 中使用'orderBy”订购相关模型?的详细内容。更多信息请关注PHP中文网其他相关文章!

    声明:
    本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn