【问题标题】:Laravel 8 + MSSQL - ODBC driver queries invalid column using my Eloquent class nameLaravel 8 + MSSQL - ODBC 驱动程序使用我的 Eloquent 类名查询无效列
【发布时间】:2021-08-25 12:19:43
【问题描述】:

所以我有 2 个模型 - OrderFile,但我将类命名为 EloquentOrderEloquentFile,因为我必须这样做。

订单可以有很多文件:

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

文件属于顺序:

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

订单栏:

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');
});

文件列:

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');
});

我创建了新订单……

…我用它的主键来创建新文件。

当我尝试使用文件获取订单时,我得到 ODBC 异常:

$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]列名无效 'eloquent_order_uuid'。 (SQL: select * from [files] where [文件].[eloquent_order_uuid] 在 (A3B92A50-04E6-48B8-A7CC-E8128790D738)) 在文件中 /var/www/html/vendor/laravel/framework/src/Illuminate/Database/Connection.php 在第 685 行

我明白为什么会这样了:没有eloquent_order_uuid 列,有order_uuid。为什么 MSSQL 与 eloquent_ 进行连接。没有它,它应该可以工作。我做错了吗?

这应该是微不足道的 - 我已经用 MySQL 做过很多次了,但从来没有用过 MSSQL 驱动程序。

【问题讨论】:

  • 您还有另一个问题:UUID 没有引号。
  • 问题已解决。见下文。这不是与报价相关的问题。

标签: php sql-server laravel


【解决方案1】:

我认为您必须通过传递 foreign keylocal key 来更新关系

EloquentOrder 模型中

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

EloquentFile 模型中

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

还在模型中添加$primaryKey 属性

protected  $primaryKey="uuid";

同时提及表名

 protected $table="orders"  in EloquentOrder model

 protected $table="files"  in EloquentFile model 

【讨论】:

  • 好的,我忘记了hasManybelongsTo 之后的第二个和第三个参数。我已经指定了表属性。谢谢!
  • @MattKomarnicki。哦好吧.np :)
猜你喜欢
  • 2020-11-25
  • 1970-01-01
  • 1970-01-01
  • 2016-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-04
  • 1970-01-01
相关资源
最近更新 更多