需要在三个模型之间建立关系

问题描述 投票:0回答:2

我们有一个可以通过多种方式学习的用户。在每个方向上,用户都有一定的水平。有三种模式:用户,方向,级别。它们需要以这样一种方式链接,即用户可以获得其方向列表,并在每个方向上获得其级别。例如,$user->directions[0]->level

再一次关于这段关系。用户可以有许多方向,并且方向很多用户(多对多)。方向可以有多个级别,但级别只有一个方向(一个到多个)。

我使用Laravel 5.8。

laravel eloquent relationship
2个回答
1
投票

由于用户有很多方向,而方向有很多用户,你应该使用belongsToMany(与数据库的多对多关系有关的雄辩关系。)关系。

并且一个方向有很多级别但是一个级别只有一个方向你应该分别在方向和水平上使用hasManybelongsTo

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    public function directions()
    {
        return $this->belongsToMany(Direction::class);
    }
}
use Illuminate\Database\Eloquent\Model;

class Direction extends Model
{
    public function levels()
    {
        return $this->hasMany(Level::class);
    }

    public funciton users()
    {
        return $this->belongsToMany(User::class);
    }
}
use Illuminate\Database\Eloquent\Model;

class Level extends Model
{
    public function direction()
    {
        return $this->belongsTo(Direction::class);
    }
}

UPDATE

如果您尚未定义数据库表。这就是你如何做到的。

您可以使用Laravel迁移来创建数据库表。

用户表

Schema::create('users', function (Blueprint $table) {
            $table->increment('id')->primary();
            // all the other columns goes here.
});

方向表

Schema::create('directions', function (Blueprint $table) {
            $table->increment('id')->primary();
            // all the other columns goes here.
});

用户表的方向

Schema::create('direction_user_table', function (Blueprint $table) {
            $table->unSignedInteger('user_id');
            $table->unSignedInteger('direction_id');
            // all the other columns goes here.
});

级别表

Schema::create('levels', function (Blueprint $table) {
            $table->increment('id')->primary();
            $table->unSignedInteger('direction_id');
            // all the other columns goes here.
});

1
投票

您可以在laravel模型中使用以下关系。

对于用户模型

public function directions()
{
    return $this->hasMany('App\Direction','user_id');
}

对于Direction模型

public function users()
{
    return $this->hasMany('App\User','id','user_id');
}

public function levels()
{
    return $this->hasMany('App\Level','direction_id');
}

对于Level模型

public function direction()
{
    return $this->hasOne('App\Direction','id','direction_id');
}
© www.soinside.com 2019 - 2024. All rights reserved.