Skip to content

Generate Active Record models #147

@Tigrov

Description

@Tigrov

https://github.com/yiisoft/yii-gii/blob/master/src/Generator/ActiveRecord/Generator.php

Model generation needs to be improved to generate models with:

  1. Declared namespace;
  2. Properties according to column types, taking into account the possibility of null and default value ​​if it is an expression.
    For example, a property can have a type string|DateTimeInterface|ExpressionInterface|null for nullable datetime columns with default now();
  3. Default values ​​of properties, if any;
  4. Table name;
  5. Optionally, property visibility (private, protected, public). If private then use PrivatePropertiesTrait; must be included;
  6. Optionally, getters and setters for the properties, with using null coalescing operator return $this->id ?? null; if the property is not initialized by default and with using ActiveRecordInterface::set() method if the property used for relations;
  7. Optionally, relations with inversed relations (using foreign keys);
  8. Optionally, other functionality using existing traits.

For example:

declare(strict_types=1);

namespace App\Model;

use Yiisoft\ActiveRecord\ActiveQueryInterface;
use Yiisoft\ActiveRecord\ActiveRecord;
use Yiisoft\ActiveRecord\Trait\RepositoryTrait;

final class User extends ActiveRecord
{
    use RepositoryTrait;

    protected int $id;
    protected string $username;
    protected string $status = 'active';

    public function tableName(): string
    {
        return '{{%user}}';
    }

    public function getId(): ?int
    {
        return $this->id ?? null;
    }

    public function setId(int $id): void
    {
        $this->set('id', $id);
    }

    public function getUsername(): ?string
    {
        return $this->username ?? null;
    }

    public function setUsername(string $username): void
    {
        $this->username = $username;
    }

    public function getStatus(): string
    {
        return $this->status;
    }

    public function setStatus(string $status): void
    {
        $this->status = $status;
    }

    public function relationQuery(string $name): ActiveQueryInterface
    {
        return match ($name) {
            'profile' => $this->getProfileQuery(),
            default => parent::relationQuery($name),
        };
    }

    public function getProfile(): ?UserProfile
    {
        return $this->relation('profile');
    }

    public function getProfileQuery(): ActiveQueryInterface
    {
        return $this->hasOne(UserProfile::class, ['id' => 'id'])->inverseOf('user');
    }
}

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions