Laravel Eloquent ignore attribute if not in table during insert

前端 未结 4 1445
不思量自难忘°
不思量自难忘° 2021-02-19 03:44

I have a model Foo that corresponds to a table with the following columns.

id
description
user_id

I\'m setting the attributes of the Foo model individual

4条回答
  •  半阙折子戏
    2021-02-19 04:49

    Just add $bar as an attribute in your foo class:

    class Foo extends Model
    {
    
      public $bar;
      //...
    

    now you can use save() and Laravel will not try to store bar in the DB.


    Explanation:

    If you call save() on a model, only those attributes that are in the array $model->attributes will be saved to the database. If you define $bar as an attribute in the class Foo, then $foo->bar ="xyz" will never end up in the array $model->attributes.

    However, if you do not have declared such an attribute for Foo, then __set() is called because you try to save something in an inaccessible property.

    You may check out Laravel\Illuminate\Database\Eloquent\Model.php:

    /**
         * Dynamically set attributes on the model.
         *
         * @param  string  $key
         * @param  mixed  $value
         * @return void
         */
        public function __set($key, $value)
        {
            $this->setAttribute($key, $value);
        }
    

    which basically calls

    $this->attributes[$key] = $value;
    

    from Laravel\Illuminate\Database\Eloquent\Concerns\HasAttributes.php.

    Now $foo->bar ="xyz" will end up beeing in $foo->attribute['bar'] and this is why save() crashes with ..this column does not exists...

提交回复
热议问题