<?php

namespace Staudenmeir\EloquentEagerLimit\Relations;

use Illuminate\Database\Query\Grammars\MySqlGrammar;

trait HasOneOrManyThrough
{
    use HasLimit;

    /**
     * Set the "limit" value of the query.
     *
     * @param int $value
     * @return $this
     */
    public function limit($value)
    {
        if ($this->farParent->exists) {
            $this->query->limit($value);
        } else {
            $column = $this->getQualifiedFirstKeyName();

            $grammar = $this->query->getQuery()->getGrammar();

            if ($grammar instanceof MySqlGrammar && $grammar->useLegacyGroupLimit($this->query->getQuery())) {
                $column = 'laravel_through_key';
            }

            $this->query->groupLimit($value, $column);
        }

        return $this;
    }
}
