<?php

namespace CliqThemes\ORM\Relations;

use CliqThemes\ORM\Model;

/**
 * Represents a one-to-many relationship between two models.
 */
class HasMany extends Relation
{
    protected string $foreignKey;

    protected string $localKey;

    /**
     * @param string $foreignKey Column on the related model referencing the parent.
     * @param string $localKey   Column on the parent model representing the key.
     */
    public function __construct(Model $parent, Model $related, string $foreignKey, string $localKey)
    {
        parent::__construct($parent, $related);
        $this->foreignKey = $foreignKey;
        $this->localKey = $localKey;
    }

    /**
     * Retrieve all related model instances.
     *
     * @return Model[]
     */
    public function getResults(): array
    {
        $value = $this->parent->{$this->localKey};

        if ($value === null) {
            return [];
        }

        return $this->newRelatedQuery()
            ->where($this->foreignKey, '=', $value)
            ->get();
    }
}

