Laravel BelongsToMany 关联中,如何对中间表里的数据进行排序

Laravel

Laravel 中的默认 belongsToMany 关系可以很好地工作-你可以轻松地附加,分离或同步记录。但是,如果要按最新或最旧的顺序对记录进行排序,该怎么办?本文将展示如何操作。

下面是对默认数据表的描述。

迁移文件:

class CreateProjectUserPivotTable extends Migration
{
    public function up()
    {
        Schema::create('project_user', function (Blueprint $table) {
            $table->unsignedInteger('project_id');
            $table->foreign('project_id')->references('id')->on('projects');
            $table->unsignedInteger('user_id');
            $table->foreign('user_id')->references('id')->on('users');
        });
    }
}

然后在模型中, 例如 app/Project.php:

public function users()
{
    return $this->belongsToMany(User::class);
}

那么,我们如何添加自动增量或时间戳字段,然后能够订购最新或最旧的数据记录呢?很简单

在迁移中,我们添加了 bigIncrements 以及 timestamps 字段:

Schema::create('project_user', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->unsignedInteger('project_id');
    $table->foreign('project_id')->references('id')->on('projects');
    $table->unsignedInteger('user_id');
    $table->foreign('user_id')->references('id')->on('users');
    $table->timestamps();
});

在模型中,我们不需要添加有关 id 字段的任何特定信息,但是对于时间戳而言,有一个特殊的方法 withTimestamps():

public function users()
{
    return $this->belongsToMany(User::class)->withTimestamps();
}

我们可以创建一个单独的关系,如下所示:

public function newest_users()
{
    return $this->belongsToMany(User::class)->orderBy('id', 'desc');
}

在 Controller 中,我们可以有以下内容:

$projects = Project::with('newest_users')->get();

如果你想从最新的开始查看项目的用户,则是这样的:

@foreach($project->newest_users as $user)
    <span class="label">{{ $user->name }}</span>
@endforeach

坦白地说,在撰写本文时,我意识到时间戳字段主要仅用于提供信息,对其进行排序并不可靠,因为在同一秒内发生并发的可能性很大。所以我的建议是按 id 字段进行排序,该字段是自动递增的,并且仅在需要了解创建条目的时间时才查看时间戳。

本文中的所有译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。

原文地址:https://laraveldaily.com/get-newest-olde...

译文地址:https://learnku.com/laravel/t/39024

本文为协同翻译文章,如您发现瑕疵请点击「改进」按钮提交优化建议
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!