Deniss Muntjans
Deniss Muntjans

Reputation: 379

Polymorphic BelongsTo relationship in Laravel

enter image description here

How could I set relationships to use just one table (model_types) in Laravel to store types for cars and bikes?

Car model

public function carTypes() 
{
   return $this->hasMany(CarType::class);
}

CarType model (inverse relationship):

public function car()
{
   return $this->belongsTo(Car::class);
}

Bike model

public function bikeTypes() 
{
   return $this->hasMany(BikeType::class);
}

BikeType model (inverse relationship):

public function bike()
{
   return $this->belongsTo(Bike::class);
}

Upvotes: 0

Views: 797

Answers (4)

Mathew Berry
Mathew Berry

Reputation: 148

There are 2 options I can think of to solve this problem, the first being a simple table using a type column and the other is using polymorphic relations which is a little overkill.


The first option is to have a type column on your model_types table which you could use to determine the type and adding constants in your ModelType class like this:

const TYPE_CAR = 1;
const TYPE_BIKE = 2;

enter image description here

Then you can easily access the data like so, so from the Car model it's

public function modelType() 
{
    return $this->belongsTo(ModelType::class)->where('type', ModelType::TYPE_CAR);
}

If you wanted to access it from the model_types table it would look like this:

public function cars()
{
    return $this->hasMany(Car::class)
}
public function bikes()
{
    return $this->hasMany(Bike::class)
}

Upvotes: 2

Hedayatullah Sarwary
Hedayatullah Sarwary

Reputation: 2844

Car Model:

public function carTypes() {
    return $this->hasMany(ModelType::class);
}

Bike Model:

public function bikeTypes() {
    return $this->hasMany(ModelType::class);
}

ModelType Model:

public function car() {
    return $this->belongsTo(Car::class, 'modeltype_car_id');
}

public function bike() {
   return $this->belongsTo(Bike::class, 'modeltype_bike_id');
}

Upvotes: 0

Anurat Chapanond
Anurat Chapanond

Reputation: 2987

You have it reversed.
A car can belong to one car type, but one car type can apply to many cars.
The same goes for bikes.

You don't need a polymorphic relationship.

Car model

public function carType() 
{
   return $this->belongsTo(ModelType::class);
}

Bike model

public function bikeType() 
{
   return $this->belongsTo(ModelType::class);
}

ModelType model

public function cars()
{
   return $this->hasMany(Car::class);
}

public function bikes()
{
   return $this->hasMany(Bike::class);
}

Upvotes: 1

Farid
Farid

Reputation: 772

Not sure about inverse relationship, but in your Car model you should use

public function carTypes() 
{
   return $this->hasMany(ModelType::class, 'foreign_key', 'local_key');
}

Upvotes: 0

Related Questions