【发布时间】:2020-02-06 14:15:39
【问题描述】:
我是 Laravel 的初学者。我在我的项目中使用 Laravel 5.8。
我有这个代码:
$product = new Product();
$product->create([
'company_id' => $request->user()->company_id,
'enable' => $request->input('enable') ?? 0,
'id_delivery_vat' => $request->input('id_delivery_vat') ?? 1,
'id_product_vat' => $request->input('id_product_vat') ?? 1,
'id_producer' => $request->input('id_producer'),
'promo' => $request->input('promo') ?? 0,
'name' => $request->input('name'),
'qr_code' => $request->input('qr_code'),
'oe_code' => $request->input('oe_code'),
'description' => $request->input('description'),
'product_price' => str_replace(",", ".", $request->input('product_price')) ?? 0,
'promo_product_price' => str_replace(",", ".", $request->input('promo_product_price')) ?? 0,
'product_delivery_price' => str_replace(",", ".", $request->input('product_delivery_price')) ?? 0,
'quantity' => $request->input('quantity'),
'url_address' => Str::slug($request->input('name'), '-')
]);
如何获取最后插入 ID?
我的产品迁移:
Schema::create('products', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('company_id')->unsigned();
$table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade');
//$table->bigInteger('category_id')->unsigned();
//$table->foreign('category_id')->references('id')->on('product_categories');
$table->smallInteger('id_delivery_vat')->unsigned();
$table->foreign('id_delivery_vat')->references('id')->on('vat');
$table->smallInteger('id_product_vat')->unsigned();
$table->foreign('id_product_vat')->references('id')->on('vat');
$table->bigInteger('id_producer')->unsigned();
//$table->foreign('id_producer')->references('id')->on('product_producers');
$table->string('name', 120)->nullable();
$table->string('qr_code', 120)->nullable();
$table->string('oe_code', 120)->nullable();
$table->char('enable', 1)->default(0);
$table->char('promo', 1)->default(0);
$table->longText('description')->nullable();
$table->decimal('product_price', 9, 2)->default(0);
$table->decimal('promo_product_price', 9, 2)->default(0);
$table->decimal('product_delivery_price', 9, 2)->default(0);
$table->unsignedInteger('quantity')->default(0);
$table->string('url_address', 160);
$table->timestamps();
$table->engine = "InnoDB";
$table->charset = 'utf8mb4';
$table->collation = 'utf8mb4_unicode_ci';
});
我的 ID 有很大的增量。
型号:
class Product extends Model
{
use scopeActiveTrait;
protected $fillable = ['company_id', 'id_delivery_vat', 'id_product_vat', 'id_producer', 'name', 'qr_code', 'oe_code', 'enable', 'promo', 'description', 'product_price', 'promo_product_price', 'product_delivery_price', 'quantity', 'url_address'];
protected $quarded = ['id'];
public $timestamps = true;
public function categories()
{
return $this->belongsToMany(Category::class, 'product_selected_categories', 'product_id', 'category_id');
}
}
我该如何修复它? 我尝试:$product->id, $product->nextId() - 但这不起作用:(
【问题讨论】: