mercredi 30 janvier 2019

Three way pivot table get all teams a user belongs to and the roles for each team

I am using a belongsToMany relationship between users, teams, and the roles tables.

What I want to do is get all teams that an authenticated user belongs too and get all of the roles the user has for that team under. Then I want to output the it to JSON. (I'm not using blade).

User Frank:

Team 1:

  • Manager
  • Player

Team 2:

  • Manager

Team 5:

  • Player

Query output to show relations

return User::first(1)->with('teams','roles')->get();

Output:

{  
   "id":1,
   "username":"Frank",
   "name":"Frank",
   "email":"frank@example.com",
   "teams":[  
      {  
         "id":21,
         "name":"Team 1",
         "pivot":{  
            "user_id":1,
            "team_id":21,
            "role_id": 1
         }
      },
      {  
         "id":1,
         "name":"Team 2",
         "pivot":{  
            "user_id":1,
            "team_id":1,
            "role_id":1
         }
      },
      {  
         "id":3,
         "name":"Team 5",
         "pivot":{  
            "user_id":1,
            "team_id":3
            "role_id":2
         }
      }
   ],
   "roles":[  
      {  
         "id":1,
         "name":"Manager",
         "pivot":{  
            "user_id":1,
            "role_id":1,
            "team_id":21
         }
      },
      {  
         "id":2,
         "name":"Player",
         "pivot":{  
            "user_id":1,
            "role_id":2,
            "team_id":21
      },
      {  
         "id":1,
         "name":"Manager",
         "pivot":{  
            "user_id":1,
            "role_id":1,
            "team_id":1
         }
      },
      {  
         "id":2,
         "name":"Player",
         "pivot":{  
            "user_id":1,
            "role_id":2,
            "team_id":3
         }
      }
   ]
}



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2FYKNNg
via IFTTT

Aucun commentaire:

Enregistrer un commentaire