Many to Many Relationship - Models

Nov 21, 2016 manytomany relationships migration database schema
WhatsApp
Previously we set up our migrations for our database in Part 1. Now these migrations need to be reflected within our model so once we query our model we can retrieve the information from the database.

Reference
https://laravel.com/docs/5.1/eloquent-relationships

class Post extends Model
{
….

//Get the tags associated with the given article
//belongsToMany you're telling Laravel that this table holds the foreign key that connects it to the other table
public function tags() {
return $this->belongsToMany('App\Tag', 'posts_tags', 'posts_id', 'tags_id')->withTimestamps();
}
}

class Tag extends Model
{

//Get the articles associated with the given tag
//belongsToMany you're telling Laravel that this table holds the foreign key that connects it to the other table
public function post() {
return $this->belongsToMany('App\Post', ‘posts_tags’, ‘posts_id’, ‘tags_id’) withTimestamps();
}
}


For a many to many relationship both model will use the belogsToMany method. I’ve had to also explicity label my columns because the table doesn’t use the default column names. I believe Eloquent assumes primary/foreign key ids are labelled ‘id’. It should also be written in the documentation in the link above

 belongsToMany(, , , )


We’ve finished defining the relationships for our models. But as a reminder for myself or you, I’ll also go over the hasMany, hasOne, belongsTo. One is the inverse of the other unless it’s a many to many relationship. As a note belongsTo/Many should be used by the foreign key table/model and hasOne/Many by the primary key table i.e. We have a Post and Author model, in a many to one relationship, many posts for one author. An author_id (Foreign key) could be in the post table. So when trying to get the author from the post model we’d use belongsTo. On the Author model we’d have the related primary key ‘id’, to get the post of the author we’d use hasMany.

So for example for a one to many relationship an author can have many blog posts (hasMany) but a blog post can only have one author (belongsTo). A many to one relationship is the same as one to many just from a different point of view.

TL;DR
As a note belongsTo/Many should be used by the foreign key table/model and hasOne/Many by the primary key table.

If you found the following info helpful, I'm happy to accept any donations of the following cryptocurrencies.

  • Bitcoin - 17DTiPExzP9StqveW428acEyB4mVMfKbiK
  • Ethereum - 0x87B8307FD20dc90cc05c94905Ec593134D32B6FF
  • Litecoin - LZMiz5U5sVq9doMLYE3gfLJrxCQDKuyCmU
  • Neo - AXv71WB38ajc1KUUEnxQKhynLLPc4BapVb