gpt4 book ai didi

php - 无效的 ID Laravel Eloquent

转载 作者:行者123 更新时间:2023-11-29 03:22:42 25 4
gpt4 key购买 nike

我面临着 Laravel 5.2 Eloquent 非常奇怪的行为。当我尝试在我的表中插入一行时,它返回一个具有递增 ID 的对象。现在的问题是,它返回的 ID 不是该行的 ID。

例如

我的代码:

    DB::beginTransaction();

//create a new product
$product_p = new Product();
$product_p->name = $request->name;
$product_p->barcode = $request->barcode;
$product_p->sale_price = $request->sale_price;
$product_p->save();
echo $product_p->id; //this gives invalid ID
DB::commit();

当我尝试访问 $product_p->id 时,它返回 31,即使数据库中的产品 ID 是 5。

我开发了同步 Controller ,它负责记录每个执行的查询,在进一步调查中我发现同步 Controller ID 负责无效 ID。

我的路线文件

// SyncController
\Event::listen('Illuminate\Database\Events\QueryExecuted', function ($query) {
$sync = new \App\Http\Controllers\SyncController();
$sync->addOperation($query->sql, $query->bindings);
});

我的同步 Controller

        DB::beginTransaction();
$sync = New Sync();
$sync->action = $sql;
$sync->data = json_encode($data);
$sync->save();
DB::commit();

我的产品数据库结构

id Primary  int(10)     UNSIGNED    AUTO_INCREMENT
name varchar(255)
barcode int(11)
sale_price int(11)

这是我的产品迁移

        Schema::create('products', function(Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('barcode')->unique();
$table->integer('sale_price');
$table->timestamps();
});

最佳答案

在 Controller 中的 store 方法中试试这个。

$input_data = $request->all();
$last_inserted_data = YourModelName::create($input_data);
dd($last_inserted_data)

检查 dd() 的输出

关于php - 无效的 ID Laravel Eloquent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41269609/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com