Matt Komarnicki
Matt Komarnicki

Reputation: 5422

Laravel 8 + MSSQL - ODBC driver queries invalid column using my Eloquent class name

So I have 2 models - Order and File, but I named classes like EloquentOrder and EloquentFile because I had to.

Order can have many files:

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

File belongs to order:

public function order(): BelongsTo
{
    return $this->belongsTo(EloquentOrder::class);
}

Columns for Orders:

Schema::create('orders', function (Blueprint $table) {
    $table->uuid('uuid');
    $table->string('index')->unique();
    $table->string('state');
    $table->string('short_name')->unique();
    $table->string('project_mass')->nullable();
    $table->string('customer')->nullable();
    $table->string('type')->nullable();
    $table->date('start_date')->nullable();
    $table->date('finish_date')->nullable();
    $table->timestamps();

    // Indexes
    $table->primary('uuid');
});

Columns for Files:

Schema::create('files', function (Blueprint $table) {
    $table->uuid('uuid');
    $table->text('name');
    $table->unsignedBigInteger('size');
    $table->text('mime_type');
    $table->string('checksum')->unique();
    $table->uuid('order_uuid');
    $table->timestamps();

    // Indexes
    $table->primary('uuid');
});

I've created new Order…

enter image description here

…and I used it's primary key to create new file.

enter image description here

As soon as I try to fetch order with files I get ODBC exception:

$order = $this->orderRepository
    ->where('uuid', '=', 'a3b92a50-04e6-48b8-a7cc-e8128790d738')
    ->with([
        'files',
    ])
    ->all();

Illuminate\Database\QueryException: SQLSTATE[42S22]: [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid column name 'eloquent_order_uuid'. (SQL: select * from [files] where [files].[eloquent_order_uuid] in (A3B92A50-04E6-48B8-A7CC-E8128790D738)) in file /var/www/html/vendor/laravel/framework/src/Illuminate/Database/Connection.php on line 685

I see why this is happening: There is no column eloquent_order_uuid, there is order_uuid. Why MSSQL makes a concatenation with eloquent_. Without it it should be working. Am I doing something wrong?

This should be trivial - I've done this multiple time with MySQL but never with MSSQL driver.

Upvotes: 0

Views: 624

Answers (1)

John Lobo
John Lobo

Reputation: 15319

I think you have to update relationship by passing foreign key and local key

In EloquentOrder Model

public function files(): HasMany
{
    return $this->hasMany(EloquentFile::class,'order_uuid','uuid');
}

In EloquentFile model

public function order(): BelongsTo
{
    return $this->belongsTo(EloquentOrder::class,'order_uuid','uuid');
}

Also add $primaryKey property in model

protected  $primaryKey="uuid";

Also mention table name

 protected $table="orders"  in EloquentOrder model

 protected $table="files"  in EloquentFile model 

Upvotes: 1

Related Questions