简体   繁体   中英

join three table relation by laravel eloquent model

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM