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

Waltu's avatar
Level 1

Problem with Polymorphic relations

Hello,

I started using polymorphic relations in my project and I got stuck!

In this case, I have 3 tables.

Project - id

Job (Polymorphic table) - project_id - job_id - job_type

InstallationJob - id - date

What kind of relation I need to my Project model to make new InstallationJob Entity? Example: $project = new Project;

$project->job()->save(new InstallationJob);

Atm I have: class Project {

public function job() { return $this->hasMany(Job::class); } }

which returns all type of Jobs. But is not working for creating new Installation Job

0 likes
1 reply
davorminchorov's avatar

Your relationships are most likely wrong.

If Job is your polymorphic relationship then they should be

class Job extends Model 
{
    // think of a better general name for the polymorphic name.
    public function jobable() 
    {
        return $this->morphTo('jobable');
    }
}
class InstallationJob extends Model 
{
    
    public function jobs() 
    {
        return $this->morphMany(Job::class, 'jobable');
    }
}
class  Project extends Model 
{
    
    public function jobs() 
    {
        return $this->morphMany(Job::class, 'jobable');
    }
}

Please or to participate in this conversation.