使用Laravel Eloquent模型连接三个表关系。

huangapple go评论67阅读模式
英文:

join three table relation by laravel eloquent model

问题

User

id
email
password

specialities

id
name
active

results

id
specialitie_id
user_id
result
color

我有三个表格,如下所示:

用户(User)

id
email
password

专业领域(specialities)

id
name
active

结果(results)

id
specialitie_id
user_id
result
color

我试图将结果(results)与其他两个表格关联起来,但我不知道如何做。下面是我的模型关系,请纠正我是否有任何问题。由于关系错误,我无法获取数据。

结果模型(Result Model)

class Result extends Model
{
    use HasFactory;
    protected $guarded = [];

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function speciality()
    {
        return $this->belongsTo(Speciality::class);
    }
}

用户模型(User Model)

class User extends Authenticatable implements MustVerifyEmail
{

    public function results()
    {
        return $this->hasMany(Result::class);
    }

}

我希望能够在Laravel中正确获取我的关系数据库表格的结果。

英文:

I have three table which is explained below

User

id
email
password

specialities

id
name
active

results

id
specialitie_id
user_id
result
color

i am trying to relate results with the rest of the 2 tables, but i don't know how to do it, below is my model relation, please correct me if there's any issue, i can't fetch the data due to having wrong relation

Result Model

class Result extends Model
{
    use HasFactory;
    protected $guarded = [];

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function speciality()
    {
        return $this->belongsTo(Speciality::class);
    }
}

User Model

class User extends Authenticatable implements MustVerifyEmail
{

    public function result()
    {
        return $this->hasMany(Result::class);
    }

}

i am trying to expect a correct result of my relation database tables in laravel

答案1

得分: 2

由于results表是Intermediate Table Columns,请使用Laravel的belongsToMany方法,因此无需创建results模型。将results表视为中间表。

在User模型中添加以下关系:

public function specialities()
{
    return $this->belongsToMany(Speciality::class, 'results')->withPivot('result', 'color');
}

还可以在Many To Many Relationships中查看更多信息。

英文:

Since the results table is Intermediate Table Columns.use laravel belongsToMany method so no need to create results model.Treat results table as pivot table.

In User Model add relation like below

public function specialities()
{
    return $this->belongsToMany(Speciality::class,'results')->withPivot('result','color');
}

Also read here Many To Many Relationships

huangapple
  • 本文由 发表于 2023年1月9日 15:24:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/75054196.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定