【问题标题】:Laravel query is looking for column which doesn't existLaravel 查询正在寻找不存在的列
【发布时间】:2017-07-25 05:09:12
【问题描述】:

我有在产品创建过程中上传图片的功能。这是控制器中createSubmit中的函数

public function productsCreateSubmit()
{

    $product = new Product;
    $product->title = Input::get('title');
    $product->price = Input::get('price');
    if (Input::hasFile('image')) {
        $file = Input::file('image');
        $filename = str_random(20);
        $file->move('uploads/', $filename . '.' . $file->getClientOriginalExtension());
        $imagePath = 'uploads/' . $filename . '.' . $file->getClientOriginalExtension();
        $image = Image::make($imagePath);

        if ($image->width() > 200) {
            $image->resize(200, null, function ($constraint) {
                $constraint->aspectRatio();
            });
        }
        if ($image->height() > 200) {
            $image->resize(null, 200, function ($constraint) {
                $constraint->aspectRatio();
            });
        }
        $image->save();
    } else {
        $imagePath = 'default.png';
    }
    $product->image = $imagePath;
    $product->save();
    return Redirect::to('/admin/products');
}

当我点击提交时,我收到数据库中的列没有默认值的错误。

SQLSTATE[HY000]:一般错误:1364 字段“file_id”没有默认值(SQL:插入到productstitlepriceimage)值(测试,1,上传/awy3CvVHLajER1E1gfpu.jpg))

问题是我的表中没有这样的列。这是产品型号

class Product extends Eloquent 
{
    protected $table = 'products';
    protected $primaryKey = 'product_id';
    public $timestamps = false;        
}

laravel 如何决定插入/查找该字段?

【问题讨论】:

  • 能否添加产品表的迁移文件
  • 我没有为此迁移。它是直接在phpmysql中创建的
  • 即使在控制器中不使用,你确定数据库中没有该列吗?
  • 我有,但我没有在控制器的 save() 语句中的任何地方使用它
  • 不管你不使用它,Eloquent 是。为列设置默认值,该功能将起作用。

标签: laravel laravel-5


【解决方案1】:

如果您的数据库表中有file_id 列,请转到phpmyadmin 中的表结构,然后单击file_id 列前面的change,然后设置属性default to NULL 并勾选Null checkmark。 点击保存!

重新运行项目!

【讨论】:

    【解决方案2】:

    这与 laravel 无关,您的数据库中有一个 file_id 字段,它没有默认值,可能您也有一个 files 表。

    虽然保存 laravel 只设置了三个字段:titlepriceimage 但不是 file_id 并且由于 file_id 没有默认值 mysql 不知道要填充什么并返回错误。

    您可以将file_id 更改为可空,并将其默认值设置为空。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-24
      • 1970-01-01
      • 2020-03-16
      • 2014-08-09
      • 1970-01-01
      • 1970-01-01
      • 2012-09-12
      • 1970-01-01
      相关资源
      最近更新 更多