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
CodePudding user response:
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