Laravel 5 - Query Multiple Associative Tables in Database

- 1 answer

Ad

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?

Ad

Answer

Ad

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.

Ad
source: stackoverflow.com
Ad