Laravel 5 - Query Multiple Associative Tables in Database
Description:
I'm working on a database setup that's requiring that I use multiple associative tables and I want to know how associative tables work within Laravel while taking advantage of the Eloquent Relationships.
I have a dataset containing soccer games. I need to store players, games, and specific player information for a game. So my structure should look something like:
Player Table:
+------------+---------+
| id | integer |
+------------+---------+
| name | string |
+------------+---------+
| team | string |
+------------+---------+
| country | string |
+------------+---------+
| average | string |
+------------+---------+
| updated_at | Date |
+------------+---------+
| created_at | Date |
+------------+---------+
Game Table
+--------------+---------+
| id | integer |
+--------------+---------+
| name | string |
+--------------+---------+
| country | string |
+--------------+---------+
| tournament | string |
+--------------+---------+
| score | string |
+--------------+---------+
| started_at | Date |
+--------------+---------+
| ended_at | Date |
+--------------+---------+
| updated_at | Date |
+--------------+---------+
| published_at | Date |
+--------------+---------+
The issue being that I need a table that associates the two together as a player can have many games and a game has many players.
Question:
How would I go about structuring my code?
- Do I write a
player_game
model? - Do I store associations in a different way than usual because this is Laravel?
Intuitively I would want to write a player_game
migration that contains game specific information for a player. But how does that work with Laravel 5 and the hasMany()
attributes?
Answer
Follow your intuition. You were right, what you are looking for is called a Many to Many Relationship.
Create the intermediate table and then you can play with different queries, if Laravel HasMany type methods doesn't fill your needs, you can always query the intermediate table directly.
Related Questions
- → "failed to open stream" error when executing "migrate:make"
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS create a multi select Form field
- → October CMS - Conditionally Load a Different Page
- → How to disable assets combining on development in OctoberCMS
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → OctoberCms component: How to display all ID(items) instead of sorting only one ID?
- → In OctoberCMS how do you find the hint path?
- → How to register middlewares in OctoberCMS plugin?