Search code examples
mysqldatabaseeloquentmany-to-manylaravel-5.1

Laravel 5.1, Eloquent, ManyToMany with comment


I followed Jeffrey Way's ManyToMany tutorial https://laracasts.com/series/laravel-5-fundamentals/episodes/21 and I got everything and everything is working great. However I would like to add another feature to my many to many relation and that is a 'comment' that gives some more info to the object relation.

I have two models:

Article [id, title, text] Category [id, title]

And this is a many to many relation so I create a pivot table as article_category. This table has two columns article_id and category_id and they are connected via functions in model as:

Article.php:

public function categories()
{
    return $this->belongsTo('App\Category');
}

& Category.php

public function articles()
{
    return $this->belongsTo('App\Article');
}

However I would like to add another field called comment to the pivot table where I could describe why this Article was added to this specific Category. Adding a column is not a problem but I don't know how to retrieve this comment from, lets say, Article instance:

$articleCategoryComment = Article::find(1)->commentFromPivotTable;

I could always define another oneToMany relation, and create another table to save the comment with fields [artice_id,category_id,comment] but I am wondering is there a better/simpler way.

Also, any good resource on database structuring will be greatly appreciated. I would prefere bunch of examples on how to do stuff right way in MySQL but a book that explains things from scratch is also good recommendation. However, at the moment I won't have time to go too deep but it will be bookmarked for future reading.

Thanks!


Solution

  • You should be using belongsToMany on a Many to Many relationship. If you want additional columns on your pivot table, using the withPivot() method. From the docs:

    return $this->belongsToMany('App\Role')->withPivot('column1', 'column2');
    

    You'll find more info here: http://laravel.com/docs/master/eloquent-relationships#many-to-many