即使我忽略了它,Laravel Eloquent仍然会在updated_at列中抛出错误

问题描述 投票:1回答:2

我正在使用Laravel 5.2开发一个网站。我正在使用数据库。所以我用Laravel雄辩的模型来使代码整洁干净。但是,即使我已经忽略它,我的一个Eloquent也在扔unknown updated_at column exception

我在我的实体中忽略或覆盖了这样的内置函数。

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    //
    protected $fillable = ['name', 'mm_name'];

    public function setUpdatedAt($value)
    {
    // Do nothing.
    }   

    public function setCreatedAt($value)
    {
    // Do nothing.
    }   
}

我从类别表中删除了updated_at列。因此,如果我更新类别,则应忽略updated_at列。

这样更新了

function updateCategory($bag)
    {
        $category = Category::find($bag->id);
        if($category)
        {
            $category->name = $bag->name;
            $category->mm_name = (empty($bag->mm_name))?$bag->name:$bag->mm_name;
            $category->save();
        }
    }

但它仍然抛出这个错误

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'updated_at' in 'field list' (SQL: update `categories` set `name` = sdsd, `mm_name` = sdsd, `updated_at` = 2016-02-20 11:36:41 where `id` = 4)

我覆盖了其他表格和雄辩的实体。这一切都有效,但事实并非如此。我该如何解决这个问题?

这是类别表的截图:

enter image description here

php laravel laravel-5.2
2个回答
1
投票

如果您没有使用created_atupdated_at字段,则需要将模型上的$timestamps属性设置为false。此外,您不需要覆盖setUpdatedAt()setCreatedAt()方法。

class Category extends Model
{
    protected $fillable = ['name', 'mm_name'];

    public $timestamps = false;
}

如果$timestamps为true,则只要更新模型,Eloquent查询构建器就会在updated_at字段中添加。


0
投票
  • 你的变异者定义是错误的。它应该是setUpdatedAtAttribute和setCreatedAtAttribute
  • 无需从数据库中删除updated_at和deleted_at属性。
  • 您已从数据库中删除了属性,因此模型中不需要setUpdatedAtAttribute和setCreatedAtAttribute。 Laravel会将它们作为数据库中的列包含在内。
  • 建议您在类别表中重新创建updated_at和created_at,如果您使用的是mysql 5.7,请确保您的时间戳不是00-00-00 00:00:00,即如果您手动创建它们(不建议手动创建它们) )。
© www.soinside.com 2019 - 2024. All rights reserved.