yii2yii2-api

Fetch users data with related clients data in Yiii2 api


I need to get an API response, where each client row has its associated users' data in it. like this:

clients: [
    {
      id: 1  
      name: 'client_1',
      users: [{ id: 1, name: 'user_1', clients_id: 1}, { id: 2, name: 'user_2', 
              clients_id: 1 }],
    },
    {
      id: 2
      name: 'client_2',
      users: [{ id: 3, name: 'user_3', clients_id: 2}, { id: 4, name: 'user_4', 
              clients_id: 2 }],
    },
  ]

How can I write Yii2 code for this result? Do query builder works here or do I need to use MySQL syntax?


Solution

  • I believe you have two tables those are related some how. You can achieve it by defining client relation in users table. One you defined the relation define extrafields function and add the relation there.

    In url use expand query param and mention your relation there. You are done! Sample URLhttp://localhost/users?fields=id,email&expand=profile

    Check the documentation