<?php

namespace CliqThemes\ORM\Relations;

use CliqThemes\ORM\Model;

/**
 * Represents a one-to-one relationship between two models.
 */
class HasOne 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 the single related model instance.
     */
    public function getResults(): ?Model
    {
        return $this->newRelatedQuery()
            ->where($this->foreignKey, '=', $this->parent->{$this->localKey})
            ->first();
    }
}

