Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Santouryuu's avatar

[Solved]Has one through

Hi, I'm aware that there are multiple questions about linking three tables, but none of them have helped me create a solution. So I have 3 models, project, task and productType. they look like this:

Project:

    public function task(){
        return $this->hasMany('App\Models\Task', 'tasks_project_id', 'project_id');
    }

Task:

    public function project(){
        return $this->belongsTo('App\Models\Project');
    }
    public function producttypes(){
        return $this->hasOne('App\Models\ProductTypes', 'product_types_id', 'tasks_product_type');
    }

ProductType:

    public function task(){
        return $this->belongsTo('App\Models\Task');
    }

One project can contain multiple tasks each task has a producttype. product types can be used multiple times with different tasks.

I can get task information using: $project->task->task_name

But using $project->task->producttypes->product_type_name gives an error Also $task->producttypes->product_type_name doesn't work either

0 likes
1 reply
Santouryuu's avatar

Kept trying and it solved the problem, still no idea why it didn't work at first. My apologies for bothering.

Please or to participate in this conversation.