yii2-rest-client icon indicating copy to clipboard operation
yii2-rest-client copied to clipboard

Relation Handling

Open mootensai opened this issue 2 years ago • 3 comments

I could get the relation response if I use join() to add expand to the request. But it get error when it try to populate the model like this image below

image

I've follow the convention mentioned in the readme that uses both the primary model & the child model. using array declaration when its one to many, but still, the problem persists.

 * @property-read MyOtherModel $myOtherModel

do you know how to fix it? or have you encounter similar problem?

mootensai avatar Sep 22 '23 16:09 mootensai

What do your classes look like? DemoAddress and User?

simialbi avatar Sep 22 '23 16:09 simialbi

let's use User & Role. User has many Role(s) image

use simialbi\yii2\rest\ActiveRecord;

/**
 * User
 * 
 * @property integer $id
 * @property string $username
 * @property string $email 
 * @property string $provider 
 * @property string $repeatPassword 
 * @property string $password 
 * @property string $resetPasswordToken 
 * @property string $confirmationToken 
 * @property bool $confirmed 
 * @property bool $blocked 
 * @property string $createdAt 
 * @property string $updatedAt  
 * 
 * @property-read Role[] $roles
 */
class User extends ActiveRecord {

    public $repeatPassword;

    public static function primaryKey(): array
    {
        return ['id'];
    }
}

and for Role

use simialbi\yii2\rest\ActiveRecord;

/**
 * Role
 * 
 * @property integer $id
 * @property string $name
 * @property string $description 
 * @property string $type 
 * @property string $createdAt 
 * @property string $updatedAt 
 * 
 * @property-read User $user
 */
class Role extends ActiveRecord {

    public static function primaryKey(): array
    {
        return ['id'];
    }
}

and use this command to run the query

User::find()->join('LEFT JOIN','role')->where(['id' => $id])->one()

mootensai avatar Sep 22 '23 16:09 mootensai

I could add function getRole() to make it work

class User extends ActiveRecord {

    public static function primaryKey(): array
    {
        return ['id'];
    }

    public function getRole() {
        return $this->hasMany(Role::class, []);
    }
}

but I don't know if this is according to your design or not.

mootensai avatar Sep 22 '23 17:09 mootensai