/** * Test user's checker model * * @depends testValidationAndSave * * @return User */ public function testUserChecker() { /* @var $model User */ $model = $this->getModule('Yii2')->grabFixture('users', 'activeUser1'); $this->assertInstanceOf(UserChecker::className(), $model->checker); /* @var $checker UserChecker */ $checker = $model->checker; $this->assertEquals($checker->user_id, $model->id); $attributes = ['email_checker' => [['value' => null, 'isValid' => true], ['value' => str_repeat('A', 33), 'isValid' => false], ['value' => str_repeat('A', 32), 'isValid' => true]], 'user_id' => [['value' => null, 'isValid' => false], ['value' => 'wrong integer', 'isValid' => false], ['value' => $model->id, 'isValid' => true]]]; $this->getModule('\\Helper\\Unit')->validateModelAttributes($checker, $attributes, $this); $this->assertTrue($checker->save()); // check unique user_id $newModel = new UserChecker(); $newModel->setAttributes($checker->getAttributes()); $this->assertFalse($newModel->validate()); $this->assertArrayHasKey('user_id', $newModel->getErrors()); $this->assertInstanceOf(User::className(), $checker->user); $this->assertInstanceOf(UserChecker::className(), $model->checker); $this->assertEquals($model->checker->id, $checker->id); $this->assertEquals($checker->user->id, $model->id); return $model; }
/** * Return's ActiveQuery to find user's checker. * If model not exists - create it. * * @return ActiveQuery */ public function getChecker() { if (!$this->hasOne(UserChecker::className(), ['user_id' => 'id'])->exists()) { // create new model if not exists $newModel = new UserChecker(); $newModel->user_id = $this->id; $newModel->save(); } return $this->hasOne(UserChecker::className(), ['user_id' => 'id']); }