Martin Smith Martin Smith - 2 months ago 15
PHP Question

Laravel Model Relationship. which one?

Hey there So I should start by say I was given this DB to work with. so not sure what relationship they used. What I need to be able to do eventually is get the name of the categories assigned to the articles.

basically it look like this

articles <> article_categories <> categories


article_categories being the connector

articles
|ID|header|body|ect...|


categories
|ID|parent_group|name|


article_categories
|article_id|category_id|


So I thought that maybe it was a
hasManyThrough
but only got errors. This also could be that I did the arguments wrong.

What I tried first was inside the articles model (got an error from this)

public function category(){
return $this->hasManyThrough('App\categories' , 'App\article_categories' ,'article_id' , 'category_id');
}


Hope i explain my situation. Do i need to use
has many through
or am I over complicating this?

-Thanks

Answer

no need for hasManyThrough

belongsToMany is what you need.

public function category(){
    return $this->belongsToMany('App\categories' , 'article_categories' ,'article_id' , 'category_id');
}
Comments