在 Yii2 Active Record 模型中声明属性

问题描述 投票:0回答:2

我需要在 Active Record 模型中声明属性。我想使用 PHP 8 语法。所以我就这么做了:

final class Post extends ActiveRecord
{    
    public ?int $id = null;
    public ?int $user_id = 0;
    public string $slug;
    public ?string $title = null;
    public ?string $content = null;
    public ?string $created_at = null;
    public ?string $updated_at = null;
    public ?string $published_at = null;

    public static function tableName(): string
    {
        return 'posts';
    }

    public function rules(): array
    {
        return [
            [['user_id', 'title', 'content'], 'required'],
            [['user_id'], 'integer'],
            [['content'], 'string'],
            [['slug', 'created_at', 'updated_at', 'published_at'], 'safe'],
            [['title'], 'string', 'max' => 512],
        ];
    }
}

但是现在所有字段都变得无法访问。当我将它们作为类字段删除时,一切都正常。

正如我们所见,Yii 只是删除了这些模型属性,因为我将它们声明为类属性:

SQLSTATE[HY000]:一般错误:1364 字段“user_id”没有 默认值正在执行的 SQL 是:INSERT INTO

posts
(
id
) 值(默认)

yii2 yii2-model
2个回答
2
投票

在 yii2 中的大多数活动记录模型中,您可以添加注释以获得 IDE 支持,例如自动完成功能,因为 yii2 使用魔术方法将字段解析为列。 请参阅Yii2 BaseActiveRecord所有列都存储在字段_attributes中。

所以我认为最好的方法是将文档注释添加到您的 ActiveRecord 类中,如下所示:

/**
 * @property ?int id
 * @property string slug
 * @property-read Author[] authors
 */

注意

@property-read
表示关系,并且访问
$object->authors;
$object->getAuthors();
时存在细微差别。在第一种情况下,执行关系查询并将结果作为数组返回(通过魔术方法),在第二种情况下,您将返回尚未执行的原始查询。

为了与作者的示例保持一致,关系方法将如下所示:

public function getAuthors(): ActiveQuery
{
    return $this
              ->hasMany(Author::class, ['id' => 'author_id'])
              ->viaTable('post_author', [ 'post_id' => 'id' ]);
}

0
投票

您可以在模型中声明属性,如下所示:

公共$名称;

如果要在该属性上应用任何规则,请将名称属性放入规则部分中进行定义。

© www.soinside.com 2019 - 2024. All rights reserved.