Wednesday, August 16, 2017

Yii2 Nested relations in Rest results

Leave a Comment

I have a customer table and a user table, they have a M:M relationship set in user_has_customer.

The entire application is a Rest API, and i use extraFields() and GET customers?expand=users to get the connected users when looking at customers.

user_has_customer stores some additional information on when the user was assigned to the customer and a few other fields, and several fields can have the same combination of user and customer. To be able to update or delete a relation, I need the relation id (user_has_customer.id) to be visible when looking at customers.

This function will return the customer, and its related users:

public function getUsers() {     return $this->hasMany(User::className(), ['id' => 'user_id'])         ->viaTable('user_has_customer', ['customer_id' => 'id'])         ->select(['id', 'username']); } 

This function will return the user-customer relationship:

public function getUserRelations() {     return $this->hasMany(UserHasCustomer::className(), ['customer_id' => 'id'])         ->select(["id",             "customer_id",             "user_id",             "created_by",             "created_at"]); } 

But i would like to know how i can nest these relations, so the result looks like this:

{     "id": 11148,     ....     "users": {         "id": 1,         "user_id": 1,         "added": "2017-08-01 22:23:24"         "user": {             "id": 1,             "username": "admin"         }     } } 

or even like this (like a MySQL join):

{     "id": 11148,     ....     "users": {         "id": 1,         "user_id": 1,         "added": "2017-08-01 22:23:24"         "username": "admin"     } } 

For some reason this will not work (the created SQL is correct, but the AR refuse to show the fields from user in the result):

public function getUserRelations() {     return $this->hasMany(UserHasCustomer::className(), ['customer_id' => 'id'])         ->joinWith('user', true) -       ->select('*'); } 

0 Answers

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment