【发布时间】:2021-11-02 11:46:39
【问题描述】:
我正在尝试通过属性获取活动记录。
$user = self::find()->where(["username" => $username])->one();
当我检查one() 方法时,我看到BaseActiveRecord::populateRecord($record, $row) 从数据库中获取了行。
正如您在图片上看到的,该行已检索,但由于某种原因,我的对象尚未填充。
我尝试为字段添加设置器,结果是一样的。
有人可以帮我吗?
编辑:
我检查了BaseActiveRecord 类:
public static function populateRecord($record, $row)
{
$columns = array_flip($record->attributes());
foreach ($row as $name => $value) {
if (isset($columns[$name])) {
$record->_attributes[$name] = $value;
} elseif ($record->canSetProperty($name)) {
$record->$name = $value;
}
}
$record->_oldAttributes = $record->_attributes;
$record->_related = [];
$record->_relationsDependencies = [];
}
当然,$columns[$name] 已经设置好了。
EDIT2:
这是我的整个 ActiveRecord 类:
<?php
namespace app\models\database;
use Yii;
use yii\base\Exception;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;
class Admin extends ActiveRecord implements IdentityInterface
{
/**
* @var int
*/
public int $id = 0;
/**
* @var string
*/
public string $username = '';
/**
* @var string
*/
public string $password = '';
/**
* @var string
*/
public string $auth_key = '';
/**
* @var string
*/
public string $access_token = '';
/**
* {@inheritdoc}
*/
public static function tableName(): string
{
return 'admin';
}
/**
* @param int|string $id
* @return Admin|IdentityInterface|null
*/
public static function findIdentity($id)
{
$user = self::find()->where(["id" => $id])->one();
if ($user) {
return null;
}
return new static($user);
}
/**
* @param mixed $token
* @param null $type
* @return IdentityInterface|static|null
*/
public static function findIdentityByAccessToken($token, $type = null)
{
$user = self::find()->where(["accessToken" => $token])->one();
if ($user) {
return null;
}
return new static($user);
}
public static function findByUsername($username): ?Admin
{
$user = self::find()->where(["username" => $username])->one();
if ($user) {
return null;
}
return new static($user);
}
public function validateAuthKey($authKey): bool
{
return $this->auth_key === $authKey;
}
/**
* @throws Exception
*/
public function validatePassword($password): bool
{
return $this->password === Yii::$app->getSecurity()->generatePasswordHash($password);;
}
/**
* @param bool $insert
* @return bool
* @throws Exception
*/
public function beforeSave($insert): bool
{
if (parent::beforeSave($insert)) {
if ($this->isNewRecord) {
$this->auth_key = Yii::$app->security->generateRandomString();
}
return true;
}
return false;
}
public function getAccessToken(): string
{
return $this->access_token;
}
public function getId(): int
{
return $this->id;
}
public function getAuthKey(): ?string
{
return $this->auth_key;
}
}
【问题讨论】:
-
属性值在
$_attributes属性中,属性在__get()和__set()中作为虚拟属性处理。您应该从模型中删除显式属性,然后$user->username应该可以正常工作。 -
您的意思是,从课程中删除
public $username;?累了,没用。 -
Rob006 的评论是对的。您应该在问题中添加更多代码(模型、读取属性的尝试)。您的模型或您访问属性的方式有问题。
-
首先想到的是
__get()这个魔术方法被覆盖了,没有从yii\db\BaseActiveRecord调用__get()的实现。 -
@MichalHynčica 我已经添加了整个
Admin课程。
标签: yii2