Friday, March 3, 2017

How can I do this join-table with Eloquent Relationships?

Purpose

I would like to get the total of mutual interests between all users referring to a single user, using Eloquent Relationships instead of Query Builder directly.

Table structure

users

+----+--------+
| id |  name  |
+----+--------+
|  1 | John   |
|  2 | George |
|  3 | Paul   |
+----+--------+

interests

+----+-----------+
| id |   name    |
+----+-----------+
|  1 | apple     |
|  2 | banana    |
|  3 | pineapple |
+----+-----------+

users_interests

+--------+------------+
| userId | interestId |
+--------+------------+
|      1 |          1 |
|      1 |          2 |
|      1 |          3 |
|      2 |          1 |
|      2 |          2 |
|      3 |          1 |
+--------+------------+

Example

Something like that...

[
    {
        "id": 2,
        "name": "George",
        "mutualInterests": 2,
    },
    {
        "id": 3,
        "name": "Paul",
        "mutualInterests": 1,
    }
]



via Isaac Ferreira

Advertisement