0

我不断收到错误

“SQLSTATE [42S22]:找不到列:1054 Unknown column '' in 'where 子句'”

使用 sql 输出:

    update `contactables` set `updated_at` = 2019-08-16 20:35:56, `active` = 0 where `` is null and `key_ID` = 235852

我试图在多态模型上使用雄辩的firstOrNew/firstOrCreate方法。我已经尝试了各种变体:

  $record1 = Contactable::firstOrNew(
    [
     'contactable_ID' => $location_ID,
     'user_ID' => $user_ID,
     'contactable_type' => Location::class,
    ]);
  $record = Contactable::find($record1->key_ID);
  $record->fill(
    [
     'active' => $active,
    ]);
  $record->save();
    $primaryKey = 'key_ID';
    $guarded = [];
    $fillable = [
        'user_ID',
        'use_loc_contact_info',
        'contactable_ID',
        'contactable_type',
        'active',
        'flag',
        'print_and_save',
        'marketing',
      ];

这似乎仅在尝试更新我实际更改某些内容的记录时发生。创建记录似乎工作正常,更新我不改变任何东西的地方似乎工作。我完全不知道接下来要做什么...

我看过这些(以及其他十几个并不真正相关的):

Laravel 雄辩的 firstOrNew 方法不更新或插入

laravel auth:api 返回 SQLSTATE[42S22]: Column not found: 1054 Unknown column '' in 'where 子句' (SQL: select * from `users` where `

感谢您的帮助或新问题!

4

2 回答 2

1

我在 Laravel 5.4 中使用了这个修复,与 Kevin Foster 之前的回答非常相似,取自https://github.com/laravel/framework/issues/5517

将此插入您的 Laravel 模型中的相关表 - 插入复合键的列名代替 column1 和 column2

解决了我的问题 - 感谢之前的贡献者

/**
 * Set the keys for a save update query.
 * This is a fix for tables with composite keys
 * TODO: Investigate this later on
 *
 * @param  \Illuminate\Database\Eloquent\Builder  $query
 * @return \Illuminate\Database\Eloquent\Builder
 */
protected function setKeysForSaveQuery(Builder $query)
{
    $query
        //Put appropriate values for your keys here:
        ->where('column1', '=', $this->column1)
        ->where('column2', '=', $this->column2);

    return $query;
}

您还需要包括:

use \Illuminate\Database\Eloquent\Builder;
于 2021-06-03T15:07:38.960 回答
0

经过相当多的环顾后,我终于根据我偶然发现的这个问题找到了解决方案。我忘记了这个表有一个复合键,这是这个问题的根源。

我将它包含在我的自定义数据透视模型中,以覆盖 laravel 默认的"setKeysForSaveQuery"

可接触类扩展 MorphPivot {
    ...
    受保护的函数 setKeysForSaveQuery(Builder $query) {
        $查询
            //在此处为键设置适当的值:
            ->where('contactable_type', '=', $this->contactable_type)
            ->where('contactable_ID', '=', $this->contactable_ID)
            ->where('user_ID', '=', $this->user_ID);

        返回$查询;
    }
    ...
}

它就像一个魅力,并解决了导致雄辩地创建...where '' is null and 'key_ID' = 235852查询的问题

我还参考了以下内容,这些内容为我的解决方案提供了信息,但大部分都没有解决我过于复杂的自定义多态关系上的复合键问题。我希望这条路可以帮助别人。

Laravel 雄辩的 firstOrNew 方法不更新或插入

创建和更新 Laravel Eloquent

https://github.com/laravel/framework/issues/2393

https://github.com/laravel/framework/issues/5355

具有两个主键的 Laravel 模型更新

https://laravel.com/docs/5.7/migrations#creating-indexes

如何在 Laravel 5 的模型中放置复合键?

https://blog.maqe.com/solved-eloquent-doesnt-support-composite-primary-keys-62b740120f

https://www.reddit.com/r/laravel/comments/alrgwk/composite_key_in_table_only/

于 2019-11-21T17:59:53.893 回答