Friday, April 14, 2017

Laravel: N to N (mysql) relation using Eloquent ORM

I got 4 tables:

// Table countries
+----+------+
| Id | Name |
+----+------+
|  1 | USA  |
|  2 | GB   |
+----+------+

// Table platforms
+----+---------+
| Id |  Name   |
+----+---------+
|  1 | Windows |
|  2 | Linux   |
+----+---------+

// Table users
+----+-------+------------+-------------+
| Id | Name  | country_id | platform_id |
+----+-------+------------+-------------+
|  1 | Admin |          1 |           1 |
|  2 | Test  |          2 |           1 |
+----+-------+------------+-------------+

// Table posts
+----+-----------+------------+-------------+---------+
| Id |   Title   | country_id | platform_id | user_id |
+----+-----------+------------+-------------+---------+
|  1 | TestPost1 |          2 |           1 | 1       |
|  2 | TestPost2 |          2 |           2 | null    |
+----+-----------+------------+-------------+---------+

The database should be able to implement the following relations:

  • User (N) <-> (N) Platform
  • User (N) <-> (N) Country
  • User (0..1) <-> (N) Post
  • Post (N) <-> (N) Country
  • Post (N) <-> (1) Platform

So now I tried to implement these relations following Laravel Eloquent ORM documentation:

  // Country.php
  public function posts()
  {
      return $this->belongsToMany('App\Post');
  }

  public function users()
  {
      return $this->belongsToMany('App\User');
  }

  // Platform.php
  public function users()
  {
      return $this->belongsToMany('App\User');
  }

  public function posts()
  {
      return $this->belongsToMany('App\Post');
  }

  // User.php
  public function posts()
    {
        return $this->hasMany('App\Post');
    }

    public function countries()
    {
        return $this->hasMany('App\Country');
    }

    public function platforms()
    {
          return $this->hasMany('App\Platform');
    }

  // Post.php
  public function countries()
  {
      return $this->hasMany('App\Country');
  }

  public function platforms()
  {
      return $this->hasMany('App\Comment');
  }

  public function user()
  {
      return $this->belongsTo('App\User', 'user_id');
  }

But now I am confused, as I thought the way to implement N to N relations in mysql is to add a third table to db, for example like that:

// Table CountryUserRelations to implement User (N) <-> (N) Country
+----+------------+---------+
| Id | country_id | user_id |
+----+------------+---------+
|  1 |          1 |       1 |
|  2 |          2 |       1 |
|  3 |          1 |       2 |
|  4 |          2 |       2 |
+----+------------+---------+

But how does Eloquent ORM handle the rules inside my model? Will it keep the N to N relations without having to add a relations table? Or am I missing something or misunderstanding the Eloquent ORM Relations concept?



via HelloWorld0815

Advertisement