Skip to content
Advertisement

Laravel: How to use multiple pivot table relationships

I’m new to defining relationships and frameworks all together, I’m just used to raw SQL. Did my homework (google + Laravel documentation) but I think I’m just not understanding it properly.

Heres is the relevant information: User Table:

JavaScript

Challenges Table:

JavaScript

User_challenge_links

JavaScript

Challenge_sub_categories

JavaScript

So my goal.. user->challenges.

JavaScript

The relationships:

  • A user has many User_challenge_links
  • A User_challenge_link has a challenge_sub_categories_id (thus a challenge_sub_category)
  • A challenge_id from challenges_sub_categories matches a challenge in the challenges table

Any help, even pointing me in the right direction will be much appreciated!

Edit: example data: Users Data

JavaScript

Categories Data id name 1 “Foo” 2 “Bar”

Sub_categories Data id name 1 “SubFoo” 2 “SubBar”

Challenges Data id name 1 “Swing dat Foo” 2 “Bar all the things” 3 “Foo The Bars”

Challenge_sub_categories Data

JavaScript

User_challenge_links Data

JavaScript

Dataflow:
A user can create categories or use existing ones and link challenges to them (existing or new). However, a user can also choose to use a subcategory, which he then links to a category and link challenges to that instead.
So, a category is mandatory, but a sub_category isn’t. If however a sub_category is used (again.. existing or new) the challenge will be connected to that subcategory.

Note: A subcategory CAN be connected to multiple categories

JavaScript

These are some possible situations

Advertisement

Answer

This setup should get you going. I tried to keep the naming as simple as possible.

JavaScript

Defining your Eloquent Models

JavaScript

Using your Eloquent Models … just some examples of what you can do.

JavaScript

References and suggested reading:

Laravel Eloquent Relationships belongsTo belongsToMany hasMany

Querying relations Model::has()

Eager Loading Model::with()

Dynamic Properties for Accessing Relations Resolve $model->relationship

Inserting related Models attach() associate()

Query Scopes

Working with Pivot tables If you need to retrieve extra data from the pivot table.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement