Laravel Eloquent 没有主键 [英] Laravel Eloquent no primary key
本文介绍了Laravel Eloquent 没有主键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想更新具有复合主键的旧表.为了生成完整的更新查询,例如:
I would like to update an old table that have a composite primary key. In order to generate a full update query such as:
UPDATE foos SET (...) WHERE pk1 = ? AND pk2 = ?;
相反,Eloquent 尝试执行以下进行大规模更新的操作:
Instead Eloquent tries to do the following which does massive update:
UPDATE foos SET (...) WHERE pk1 = ?;
我将主键属性设置为 null
,如在 Google 上看到的:
I set the primary key attribute to null
as seen on Google:
class Foo extends Model {
protected $guarded = [];
protected $primaryKey = null;
public $incrementing = false;
public $timestamps = false;
}
但我收到此错误:
Illuminate\Database\QueryException: SQLSTATE[42S22]:
Column not found: 1054 Unknown column '' in 'where clause'
(SQL: update `previews` set `preview_id` = 1805 where `` is null) in
./vendor/illuminate/database/Connection.php on line 664
我想这不是 Eloquent 支持的功能,那么如何生成我的 update
查询?
I suppose this is not a supported feature of Eloquent, so how can I generate my update
query?
我的更新查询是:
$p = Foo
::where('pk1', $foo)
->where('pk2', $bar)
->first();
$p->update('column', 42);
推荐答案
不要取模型,直接在数据库中更新:
Don't fetch the model, update it directly in the database:
Foo::where('pk1', $foo)
->where('pk2', $bar)
->update(['column' => 42]);
这篇关于Laravel Eloquent 没有主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文