简体   繁体   中英

Eloquent update method throwing an error when a model has a dirty property that does not exist in the database

When adding a property that does not exist in the database on a model and I run the update method it throws an error. Please see the code below for an example.


>>> $foo = \App\Model::first()
=> App\Model {#4364
    "id": 1,
    "name": "John",
    "created_at": "2019-02-22 15:45:28",
}

>>> $foo->bar = 'bar';
=> "bar"

>>> $foo->update(['name' => 'new_name']);

Illuminate/Database/QueryException with message 'SQLSTATE[42S22]: 
Column not found: 1054 Unknown column 'bar' in 'field list' (SQL: 
update `models` set `name` = new_name, `updated_at` = 2019-02-22 
15:33:09, `bar` = bar where `id` = 1)'

The desired outcome is that it will ignore the property bar when the eloquent update method is run on foo. Does anyone know why this is happening and how to get around it?

Oooh, well when you call:

$foo->bar = 'bar';

Therefore when you now call $foo:

enter code here=> App\Model {#4364
    id: 1,
    name: "John",
    created_at: "2019-02-22 15:45:28",
    bar: "bar"
}

This adds bar to the above instance of $foo. Hence when you call update on it, this checks through all the columns and determine which ones to update and in this case bar is not a column in the db hence the error:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM