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

Sam's avatar
Level 4

MindBlank - Should I pivot?

Hi all,

So, I have 3 tables

vehicle_type, extra, extra_type

"A vehicle_type has many extras and a extra belongs to an extra_type"

I did setup a pivot table for this however looking at it, I would need to find a belongstomany relationship for this to work with the attach method. Can anyone advise on the above?

0 likes
5 replies
cipsas's avatar

Pivot table need only if vehicle_type has many-to-many relationship with extra table

Sam's avatar
Level 4

Thanks @cipsas ,

So how would I go about defining this relationship then?

As far as I understood it the relationship between vehicle_type and extra was:

class VehicleType extends Model
{
    public function extras(){
             return $this->hasMany(Extra::class);
     }
}

With the above in mind how would you attach the 'Extras' to the Vehicle type? Serialize the extras id's in a column on the vehicle_type table?

cipsas's avatar

@Sam if vehicle_type(id,....) has one-to-many relationship with extra(id,vehicle_type_id, ....) table and extra table has one-to-one relationship with extra_type(id,extra_id), then Extra.php model:

class Extra extends Model
{
    public function VehicleType (){
             return $this->belongsTo(VehicleType::class);
     }

    public function ExtraType (){
             return $this->hasOne(ExtraType::class);
     }
}

VehicleType model:

class VehicleType extends Model
{
    public function extras(){
             return $this->hasMany(Extra::class);
     }
}

ExtraType model:

class ExtraType extends Model
{
    public function extra(){
             return $this->belongsTo(Extra::class);
     }
}
Sam's avatar
Level 4

Thanks again @cipsas Sorry I should have made it a little clearer:

A 'vehicle_type' has many 'extras' but 'extras' can be assigned to many different 'vehicle_type's. An extra also has one 'extra_type'.

Please or to participate in this conversation.