Search code examples
phpormlaravel-5eloquentmany-to-many

Eloquent ORM same table relationships in Laravel 5.2


Suppose we have a fruits table like the following:

id|fruit
----------------
 1|apple
 2|pear
 3|orange
 4|lemon
 5|mandarin

and that we wanted to retrieve these fruits as variants of each other without any hierarchy and without another table for variants (no hierarchical comments->replies type of thing).

So, for example, one should be able to retrieve an $orange=Fruit::find(3)->fruitVariants;. This would ideally give us all related fruits (lemon, mandarin).

The inverse should also be possibile $lemon=Fruit::find(4)->fruitVariants; should retrieve orange and mandarin.

They should all be equivalent variants of each other and I have no idea on how to do this. A fruit_fruit table? Any ideas?


Solution

  • You are right that you need some table to store many-to-many relationship.
    This relationship is many to many because each fruit can have many variants and each variant can suit for many fruits.

    So you need such fruit_variants table:

    +---------+----------+
    |fruit_id |variant_id|
    +---------+----------+
    |        3|         4|
    |        3|         5|
    |        4|         3|
    |        4|         5|
    |        5|         3|
    |        5|         4|
    +---------+----------+
    

    And also you need to add this variants method into your Fruit model

    public function variants()
    {
        return $this->belongsToMany('Fruit', 'fruit_variants', 'fruit_id', 'variant_id');
    }