amir5's avatar
Level 7

How to have has many relationship without second model or foreign key?

I have a table called interviews and it has a column named task_response. Then I wanted to record history of responses(user can upload many task responses) but they will only update the task_response column(because I want to have one task_response file).

The new table is called task_responses and it has only interview_id and uploaded_at in it. Here I have a has many relation but I don't have a second model(I don't need to), what should I do with eloquent?

Currently the solution I'm using is to use query builder so:

public function taskResponses() {
	return DB::table('task_responses')->where('interview_id', $this->id);
}
0 likes
5 replies
shariff's avatar

Did you try calling same model?

public function taskResponses() {
	return $this->hasMany(Model::class,'interview_id');
}

1 like
martinbean's avatar
Level 80

@amir5 You should just model your data properly.

If an interview has many “task responses”, then create the appropriate models and relations:

class Interview extends Model
{
    public function taskResponses(): HasMany
    {
        return $this->hasMany(TaskResponse::class);
    }
}
class TaskResponse extends Model
{
    public function interview(): BelongsTo
    {
        return $this->belongsTo(Interview::class);
    }
}

You can then also use a has one of many relation to get the latest task response for interviews:

class Interview extends Model
{
    public function taskResponses(): HasMany
    {
        return $this->hasMany(TaskResponse::class);
    }

    public function latestTaskResponse(): HasOne
    {
        return $this->hasOne(TaskResponse::class)->latestOfMany();
    }
}
1 like
amir5's avatar
Level 7

@martinbean I've refactor to has many approach, and I should say.... It made my work easier, I don't need to check if that column has updated or not to insert to to record history, It's already in has many table...

1 like
amir5's avatar
Level 7

@martinbean Is there any hasOne for belongs to many relation? model belongs to many statuses, and I want to have something like latestStatus.

Please or to participate in this conversation.