0

I'm currently working on a laravel project, but I'm kind of stuck finding the right eloquent relations.

My tables and the connections (should) look like this: Project Relations

My model relations look like this:

User

    public function team() 
{
    return $this->hasMany(Team::class, 'user_id');
}

public function evaluation() 
{
    return $this->hasMany(Evaluation::class, 'user_id');
}

Team

public function user()
{
   return $this->belongsTo(User::class);
}
public function survey()
{
    return $this->hasMany(Survey::class, 'team_id');
}

Evaluation

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

public function survey()
{
return $this->hasMany(Survey::class, 'evaluation_id');
}

Survey

public function team()
{
return $this->belongsTo(Team::class);
}

public function evaluation()
{
return $this->belongsTo(Evaluation::class);
}

public function surveyresponse()
{
return $this->hasMany(SurveyResponse::class, 'survey_id');
}

SurveyResponse

public function survey()
{
return $this->belongsTo(Survey::class);
}

public function testquestion()
{
return $this->belongsTo('App\TestQuestion');
}

Is this the way to go? Do I need a "Has Many Through" relation here? Or a "Polymorphic Relationship"?

4

1 回答 1

0

Seems correct to me, i just didnt see the TesteQuestion model (your last relation).

Answering your question:

The HasManyThrough relation is just a shortcut for accessing distant relations via an intermediate relation, in your case: Users has many evaluations that has many surveys. With this relationship you could get all surveys from a user.

Your relation would look like this:

/** * Get all of the surveys for the user. */ public function surveys() { return $this->hasManyThrough('App\Survey', 'App\Evaluation'); } You can access this relation like this:

$user->surveys();

But you can achieve the same (without using the HasManyThrough) by doing:

$user->evaluations()->surveys();

Beware that this will return the evaluations too, not just the surveys and it requires more processing.

So i recommend you doing the HasManyThrough relationship if you pretend to access the surveys a lot.

于 2020-03-30T16:30:31.500 回答