我不断收到错误
“ SQLSTATE [42S22]:找不到列:1054未知列”,其中 条款'“
带有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 eloquent firstOrNew method doesn't update or insert
感谢您的帮助或新问题!
答案 0 :(得分: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;
答案 1 :(得分:0)
经过大量的环顾后,我终于找到了针对此based on this issue I stumbled across的解决方案。我忘记了该表具有复合键,这是此问题的根源。
我将其包含在自定义枢轴模型中,以覆盖“ setKeysForSaveQuery” 的laravel默认值:
class Contactable extends MorphPivot { ... protected function setKeysForSaveQuery(Builder $query) { $query //Put appropriate values for keys here: ->where('contactable_type', '=', $this->contactable_type) ->where('contactable_ID', '=', $this->contactable_ID) ->where('user_ID', '=', $this->user_ID); return $query; } ... }
它像一种魅力一样工作,并解决了导致雄辩地创建...where '' is null and 'key_ID' = 235852
查询的问题
我还参考了以下内容,这些内容为我提供了解决方案,但大多数情况下并未解决我过于复杂的自定义复合键多态关系问题。我希望这条路径可以帮助其他人。
Laravel eloquent firstOrNew method doesn't update or insert
Creating and Update Laravel Eloquent
https://github.com/laravel/framework/issues/2393
https://github.com/laravel/framework/issues/5355
Laravel Model with Two Primary Keys update
https://laravel.com/docs/5.7/migrations#creating-indexes
How I can put composite keys in models in 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/