Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

orbbli's avatar

About many to many relationship

Now I have a pretty standard many to many relationship by establishing 3 tables:

table a: id, value

table b: id, value

table a_b: a_id, b_id

now when i want to access table b by table a, i have a class like this:

class a extends Model { protected $table = 'a'; public function b() { return $this->hasManyThrough('a','a_b', 'a_id','id'); } }

and i get an error message of such when i call a::find(1)->b in php: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'a_b.id' in 'on clause' (SQL: select b.*, a_b.a_id from b inner join a_b on a_b.id = a.id where a.id = 25)

pretty obvious the problem is a_b.id is not editable from model definition. is it really the case? what can i do if im not possible to change the database?

0 likes
5 replies
pmall's avatar
pmall
Best Answer
Level 56

This is a belongsToMany relationship with a_b as pivot table, not a hasManyThrough (which chains two hasMany).

orbbli's avatar

Is it possible if i can know how exactly belongsToMany relationship is different from hasMany ? I am a bit confused about when to use which

pmall's avatar

@orbbli here in your example a can have many b and b can have many a. It is a many to many relationship, named as a belongsToMany b and b belongsToMany a with laravel.

A hasManyThrough is when for example Group which hasMany User which hasMany Post. Here if you want all the posts written by the users of a group, you can define a hasManyThrough relationship between Group and Post (through User).

1 like
orbbli's avatar

Thanks for the explain. One last question, so when we are defining a many-to-many relationship, is it we shouldnt use "hasMany" but rather stick with "belongsToMany" on both sides?

Please or to participate in this conversation.