我正在尝试更新具有两列“ id”和“ comp_id”的表。我只希望一次在表中存在“ comp_id”,所以我使用firstOrCreate来做到这一点。
此调用正在表中创建一条记录,因为每次我尝试执行此操作时id都会自动增加,但是未保存comp_id值。
$connections = $connectionTable->where('base_id', $baseId)->get();
$noMatchTable = new noMatch;
foreach($connections as $connection){
$rec = $noMatchTable->setTable($comparisonId.'_no_match')->firstOrCreate(['comp_id' => $connection->comp_id]);
}
我也尝试过。
$rec = $noMatchTable->setTable($comparisonId.'_no_match')->firstOrNew(['comp_id' => $connection->comp_id])->save();
在两种情况下,$ rec-> id都会显示一个新的ID。
可正确设置模型
#fillable: array:1 [
0 => "comp_id"
]
我缺少什么可怕的简单东西?
答案 0 :(得分:2)
我对此进行了一些阅读,似乎Builder.php中的updateOrCreate()
在同一文件中调用firstOrNew()
。如果您查看firstOrNew()
,它将返回一个新的模型实例,这意味着您的setTable()
将不起作用,因为新实例将包含默认表名。我喜欢这里发布的解决方案
Update the table name at runtime not working - laravel Eloquent ORM
遗憾的是,无法动态设置表名并使用updateOrCreate()