供应商表
Schema::create('suppliers', function (Blueprint $table) {
$table->id();
$table->string('supplier_name');
});
测试_供应商_表格
Schema::create('test_suppliers', function (Blueprint $table) {
$table->id();
$table->integer('supplier_id')->nullable();
$table->foreign('supplier_id')->references('suppliers')->on('id');
$table->dateTime('started_at')->nullable();
$table->dateTime('finished_at')->nullable();
$table->timestamps();
});
在这里,当我试图插入测试供应商模型时,我遇到了这个问题
foreach ($itest_suppliers_data as $itest_supplier) {
$supplier_name = $arrayhave['supplier_name'];
$supplier_id = Supplier::where('supplier_name', $supplier_name)->pluck('supplier_id');
TestSuppliers::insert([ // noticed that test_suppliers_table is empty
'started_at' => date("Y-m-d H:i:s", time()),
'supplier_id' => $supplier_id,
'finished_at' => date("Y-m-d H:i:s", time()),
]);
供应商表的架构不正确。应该是:
Schema::create('suppliers', function (Blueprint $table) {
$table->id();
$table->string('name');
});
您的下一个问题是,您的$supplier_id变量是一个id集合,而不是单个id。您应该将其更改为:
$supplier_id = Supplier::where('name', $supplier_name)->first()->id;
pluck
将返回一个集合。您需要使用value
来获得实际值:
foreach ($itest_suppliers_data as $itest_supplier) {
$supplier_name = $arrayhave['supplier_name'];
$supplier_id = Supplier::where('supplier_name', $supplier_name)->value('supplier_id');
TestSuppliers::insert([ // noticed that test_suppliers_table is empty
'started_at' => date("Y-m-d H:i:s", time()),
'supplier_id' => $supplier_id,
'finished_at' => date("Y-m-d H:i:s", time()),
]);
这里value
相当于说Supplier::where('supplier_name', $supplier_name)->first()->supplier_id
,当然这是假设你知道总会有一个结果。我认为不管怎样,对$supplier_id
进行空检查可能是明智的。