0 follower

Trait Yiisoft\ActiveRecord\Trait\MagicRelationsTrait

Trait to define {@see ActiveRecordInterface::relationQuery()} method to access relation queries of an ActiveRecord instance. Also, it defines {@see ActiveRecordInterface::relationNames()} method to get names of all relations defined in the ActiveRecord class.

Public Methods

Hide inherited methods

Method Description Defined By
relationNames() Returns names of all relations defined in the ActiveRecord class using getter methods with get prefix and Query suffix. Yiisoft\ActiveRecord\Trait\MagicRelationsTrait
relationQuery() Yiisoft\ActiveRecord\Trait\MagicRelationsTrait

Method Details

Hide inherited methods

relationNames() public method

Returns names of all relations defined in the ActiveRecord class using getter methods with get prefix and Query suffix.

public string[] relationNames ( )
throws ReflectionException

                public function relationNames(): array
{
    $methods = get_class_methods($this);
    $relations = [];
    foreach ($methods as $method) {
        if (str_starts_with($method, 'get') && str_ends_with($method, 'Query')) {
            $reflection = new ReflectionMethod($this, $method);
            $type = $reflection->getReturnType();
            if (
                $type === null
                || !is_a('\\' . $type->getName(), ActiveQueryInterface::class, true)
            ) {
                continue;
            }
            $relations[] = lcfirst(substr($method, 3, -5));
        }
    }
    return $relations;
}

            
relationQuery() public method

public relationQuery ( string $name )
$name string
throws InvalidArgumentException

If the named relation doesn't exist.

throws ReflectionException

                public function relationQuery(string $name): ActiveQueryInterface
{
    $getter = 'get' . ucfirst($name) . 'Query';
    if (!method_exists($this, $getter)) {
        throw new InvalidArgumentException(static::class . ' has no relation named "' . $name . '".');
    }
    $method = new ReflectionMethod($this, $getter);
    $type = $method->getReturnType();
    if (
        $type === null
        || !is_a('\\' . $type->getName(), ActiveQueryInterface::class, true)
    ) {
        $typeName = $type === null ? 'mixed' : $type->getName();
        throw new InvalidArgumentException(
            'Relation query method "' . static::class . '::' . $getter . '()" should return type "'
            . ActiveQueryInterface::class . '", but  returns "' . $typeName . '" type.',
        );
    }
    /** Relation name is case-sensitive, trying to validate it when the relation is defined within this class. */
    $realName = lcfirst(substr($method->getName(), 3, -5));
    if ($realName !== $name) {
        throw new InvalidArgumentException(
            'Relation names are case sensitive. ' . static::class
            . " has a relation named \"$realName\" instead of \"$name\".",
        );
    }
    return $this->$getter();
}