【问题标题】:Model::Create() method not inserting with InnoDB storage engineModel::Create() 方法没有插入 InnoDB 存储引擎
【发布时间】:2021-11-06 22:35:03
【问题描述】:

我正在尝试将新记录 customer 插入到 MySQL 数据库中,如下所示:

$customer = Customer::create(['name'=>$request->customerName,
'email'=>$request->customerEmail,
'phone'=>$request->customerPhone,
'area_id'=>$request->customerArea,
'gender'=>$request->customerGender]);
dd($customer->id);

它适用于myISAM 存储引擎并且存在新记录,但不适用于InnoDB,发布请求返回200,数据库中没有记录。而转储dd() 返回新的ID,因为它是自动递增的。 ID 已被占用,因为当我插入一条新记录时,它会为我提供一个比以前的 ID 更新的 ID,数据库中也没有记录。

这是客户模型结构:

namespace App\Models\User;

use Illuminate\Database\Eloquent\Model;

class Customer extends Model
{
    protected $fillable = [
        'name', 'phone', 'email', 'area_id', 'gender'
    ];

    protected $table = 'customers';
}

这是customers 表结构:

【问题讨论】:

  • 你试过用 save() 代替吗?
  • @JahStation,与 save() 相同的问题
  • 我不认为 100% 相关,但 id 应该被声明为 bigint(用于迁移的 bigincrementes),我使用这种问题在数据库上运行另一个查询以获得新的 id。
  • 您是否通过查询确认未插入行,以及 phpmyadmin 未显示它们的问题?
  • @levi,是的,已确认,ID 已被占用但不存在。

标签: mysql laravel innodb myisam


【解决方案1】:

在使用 InnoDB 时,您至少需要对“事务”有所了解。

如果您有autocommit=ON,则每条语句(例如INSERT)本身就是一个事务,并且会自动成为COMMITTed

如果你有autocommit=OFF,你最终必须发出COMMIT。这是因为语句(INSERTs 等)正在“事务”中收集。

后一种情况符合症状。

【讨论】:

  • 你说得对,因为我忘记提交事务了。
  • 正因为如此,我从不使用autocommit=OFF
【解决方案2】:

既然你已经创建了Customer 模型,为什么不直接使用它呢:

$customer = new Customer();
$customer->name = $request->customerName;
$customer->email = $request->customerEmail;
$customer->phone = $request->customerPhone;
$customer->area_id = $request->customerArea;
$customer->gender = $request->customerGender;
$customer->save();

PS。当然,不要忘记将您的 Customer 模型导入您的控制器

【讨论】:

  • 我试过这个方法,但同样的问题,没有插入。
  • 您确定您在 .env 文件中正确记录了您的 database 吗?
  • 我当然做到了,这就是它使用 myISAM 插入的原因。
  • 您的 Customers 表type 是否 = InnoDB
  • 是的,存储引擎是 InnoDB for Customers 表。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-12-23
  • 2011-04-25
  • 1970-01-01
  • 2016-01-11
  • 1970-01-01
  • 2012-10-02
相关资源
最近更新 更多