dimanche 20 septembre 2015

Laravel 5.1, Eloquent, ManyToMany with comment

I followed Jeffrey Way's ManyToMany tutorial http://ift.tt/1LRcx0L 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!



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire