staudenmeir / eloquent-has-many-deep

Laravel Eloquent HasManyThrough relationships with unlimited levels
MIT License
2.67k stars 157 forks source link

Alias error Self Relations hasManyDepp #232

Closed bamalik1996 closed 6 months ago

bamalik1996 commented 6 months ago

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'as vehicles2.vin_number2 = vehicles.vin_number1 inner join medallions on' at line 1

SELECT
  `vehicles`.*,
  `medallions`.`id` AS `laravel_through_key`
FROM
  `vehicles`
  INNER JOIN `vehicles` AS `vehicles2` ON `vehicles` AS `vehicles2.vin_number2` = `vehicles`.`vin_number1`
  INNER JOIN `medallions` ON `medallions`.`id` = `vehicles` AS `vehicles2.medallion_id`
WHERE
  `medallions`.`id` = 233
$this->hasManyDeep(
            Vehicle::class,
            [MedallionNumber::class, 'vehicles as vehicles2'], // Correctly specify an alias for the second occurrence of vehicles
            [
                'id',           // Foreign key on MedallionNumber table
                'medallion_id', // Foreign key on Vehicle table (aliased)
                'vin_number1'    // Foreign key on Vehicle table (aliased)
            ],
            [
                'medallion_id', // Local key on this model (assumed)
                'id',           // Local key on MedallionNumber model
                'vin_number2'    // Local key on Vehicle model (aliased)
            ]
        );
staudenmeir commented 6 months ago

Hi @bamalik1996, You need to specify the alias with the model name:

$this->hasManyDeep(
    Vehicle::class,
    [MedallionNumber::class, Vehicle::class . ' as vehicles2'],
                             ^^^^^^^^^^^^^^
bamalik1996 commented 6 months ago
Vehicle::class . ' as vehicles2'

@staudenmeir Thank you its work.