相同用户之间的关系 table

Relation between same users table

我有 3 个不同的角色(AdminCoachRunner)。一个用户只有一个角色。

问题是当我尝试将用户与角色 Coach 以及用户与角色 Runner 相关联时。逻辑应用就是这个;我可以创建跑步者和教练,但每个跑步者只属于一个教练,一个教练有很多跑步者。

如何在相同的用户 table 上处理此问题,然后在用户模型及其关系上处理此问题。

首先,您需要外键为 nullable,您可以在用户的​​ migration 文件中指定:

your_migration_file.php

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        // your columns
        $table->unsignedBigInteger('coach_id')->nullable();  // <-----
    }); //                                    ^^^^^^^^^^^^
}

Notice that doing this you won't be able to add database constrains, but this isn't necessary anyways. Also, you might need to refresh your migrations.

然后在您的 User 模型中您需要定义您的关系:

User.php

class User extends Model {

    /** a Runner has a Coach. */
    public function coach()
    {
        return $this->belongsTo(User::class, 'coach_id');
    }

    /** a Coach teaches many Runners */
    public function runners()
    {
        return $this->hasMany(User::class, 'coach_id');
    }

然后您可以查询 eager load 并限制结果:

YourController.php

public function myCoolFunction()
{
    $runners = User::with('coach')->whereNotNull('coach_id')->get();
    $coaches = User::with('runners')->whereNull('coach_id')->get();
}

当然这个查询看起来很难看,所以你也可以在你的 User 模型中定义 local query scopes

class User extends Model {

    // some code..

    public function scopeCoaches($query)
    {
        return $query->hasRole('coach'); // maybe you use a role package?            
     // return $query->whereNull('coach_id'); // or my basic approach used before
    }

    public function scopeRunners($query)
    {
        return $query->hasRole('srunner'); // maybe you use a role package?            
     // return $query->whereNotNull('coach_id'); // or my basic approach used before
    }
}

然后使用你的范围:

public function myCoolFunction()
{
    $runners = User::with('coach')->coaches()->get();
    $coaches = User::with('runners')->runners()->get();
}