I
I
Ilbiondo2018-04-17 18:19:46
Laravel
Ilbiondo, 2018-04-17 18:19:46

Eloquent ORM, how to link many-to-many tables?

Good afternoon!
There is an Ability model, a method

categories(){
return $this->belongsToMany(
'App\Category', 'ability_category', 'ability_id', 'category_id'
);}

Category model, method
abilities(){
return $this->belongsToMany(
'App\Ability', 'ability_category', 'category_id', 'ability_id'
);}

Accordingly, in addition to the categories and abilities tables, there is a joining table ability_category with fields 'ability_id', 'category_id'.
When trying to "reach out" to the title field (for example) of the categories table through the Ability ($ability->categories->title) model, it gives an error that it (the field) does not exist.
What am I doing wrong or where did I misunderstand the manual? I have re-read it dozens of times)
Thank you very much!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrey Novikov, 2018-04-17
@Ilbiondo

Relationship BelongsToMany Always returns a collection of objects. Therefore, to select a field, you need to refer to an element of this collection.

I
Ilbiondo, 2018-04-18
@Ilbiondo

The task was resolved. The error was mainly in the fact that I incorrectly passed the array, respectively, it was not displayed. Thank you all for your input, your advice helped me a lot!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question