0

I faced some problem which I cannot resolve using Laravel's Eloquent.

I have two or more (6 - exactly) objects: - ObjectA - ObjectB - ObjectC Each of these objects has a one own Variant, but a variant structure is the same for each Object, so can be common. Variant has a filed variant_type which indicates for which type of Object belongs to. How to base relation on this field?

class Variant extends Model
{
    protected $fillable = ['variant_id','name','variant_type','variant_img'];

    public function ObjectsA()
    {
        return $this->belongsToMany(ObjectA::class);
    }
    public function ObjectsB()
    {
        return $this->belongsToMany(ObjectB::class);
    }
    .
    .
    .
}

In Objects models I have relation hasOne for Variant::class. I was thinking about creating pivot tables for each Object example: objectA_variant, objectB_variant etc... but it's not the point because Object has one variant. Also, I was thinking about creating nullable columns for foreign keys (6 columns), but I am not sure it's a good way?

Please advice and thanks in advance.

bmbbambus
  • 51
  • 1
  • 6

1 Answers1

0

You should only have a Variant and an Object class. Then relationships:

Object - > hasMany Variant

Variant-> hasOne Object

And remember to have correct column names in your tables, like for example variant_id instead of variant_type.

Otherwise you will need to manually add referencing keys to your relationship definition

Bart
  • 1,889
  • 1
  • 21
  • 38
  • I think you didn't understand me well. ObjectA and ObjectB are separated models like Dog and Cat, but all have the common part = Variant. I called Objects wrongly for explaining proposes. They are Models instead of an instance of Model. – bmbbambus May 05 '18 at 12:50
  • 1
    Still correct. Sticking to your example you should have animals table. If there are different properties for them then you can divide them into further tables one by one, or group them like you did under variant_type. Otherwise it will be db design misconception... – Bart May 05 '18 at 13:07
  • So your suggestion is to extract parent entity (in my case building), put there common columns, add building_type (which indicates child Entity) and create these 6 entities(ex: Garage, Bower, SummerHouse) with columns specified for them. And relate Variant on Building level, so keep variant_id in Building entity? I hadn't look on this that way – bmbbambus May 05 '18 at 14:49