Laravel Eloquent no primary key

眉间皱痕 提交于 2020-04-30 16:35:27

问题


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 = ?; 

Instead Eloquent tries to do the following which does massive update:

UPDATE foos SET (...) WHERE pk1 = ?; 

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

But I get this error:

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

I suppose this is not a supported feature of Eloquent, so how can I generate my update query?

My update query was:

    $p = Foo
        ::where('pk1', $foo)
        ->where('pk2', $bar)
        ->first();

    $p->update('column', 42);

回答1:


Don't fetch the model, update it directly in the database:

Foo::where('pk1', $foo)
    ->where('pk2', $bar)
    ->update(['column' => 42]);


来源:https://stackoverflow.com/questions/53871297/laravel-eloquent-no-primary-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!