英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论