Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[8.x] Wraps column name inside subQuery of hasOneOfMany-relationship #38263

Conversation

uniels
Copy link
Contributor

@uniels uniels commented Aug 6, 2021

This pull request fixes an issue with specific column names (e.g. order) in a hasOne->ofMany relationship.

See example below:

class

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;

class Product extends Model
{
    // Relations
    public function frontImage(): HasOne
    {
        return $this->hasOne(ProductImage::class)->ofMany('order', 'min');
    }

    public function images(): HasMany
    {
        return $this->hasMany(ProductImage::class);
    }
}

Call

$products = Product::query()->with('frontImage')->limit(30)->get()

Without this pull request it will raise the following Exception:

Illuminate\Database\QueryException with message '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 'order) as order, `product_images`.`product_id` from `product_images` where `prod' at line 1 (SQL: select * from `product_images` inner join (select min(id) as id, `product_images`.`product_id` from `product_images` inner join (select min(order) as order, `product_images`.`product_id` from `product_images` where `product_images`.`product_id` in (...) group by `product_images`.`product_id`) as `frontImage` on `frontImage`.`order` = `product_images`.`order` and `frontImage`.`product_id` = `product_images`.`product_id` group by `product_images`.`product_id`) as `frontImage` on `frontImage`.`id` = `product_images`.`id` and `frontImage`.`product_id` = `product_images`.`product_id`)'

Please note the missing wrapping-quotes around the column name 'order' in ... select min(order) as order ...

With this pull request, the column-name will be wrapped and the result will be as expected.

@taylorotwell taylorotwell merged commit ac268af into laravel:8.x Aug 7, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants