我有一个模型,打算将输入保存到两个不同的表中,但是有错误
Symfony \ Component \ Debug \ Exception \ FatalThrowableError参数1 传递给Illuminate \ Database \ Eloquent \ Builder :: create()的 类型数组,给定的对象,在 C:\ xampp \ htdocs \ blog \供应商\ laravel \ framework \ src \ Illuminate \ Support \ Traits \ ForwardsCalls.php 在第23行
第一个表是Transaction_in
,第二个表是Transaction_in_detail
。我计划将idTransaction_in
用作2个表之间的连接器,并且该列不是primaryKey(这是一种好习惯)吗?我可以将输入保存到Transcation_in
表中,但是仍然无法将输入保存到第二表中,而且我不知道如何将idTransaction_in
列用作连接器。
public function store(Request $request)
{
$request->validate([
'supplier_name' => 'required',
'transaction_in_date' => 'required|before_or_equal:today',
'device_type_name' => 'required',
'device_brand_name' => 'required',
'device_spec' => 'required|max:255',
'price' => 'required',
'amount' => 'required',
'total_price' => 'required',
'keterangan' => 'Nullable',
]);
$transaction_in = new Transaction_in();
$transaction_in->idTransaction_in = "0";
$transaction_in->Supplier_id = $request->input('supplier_name');
$transaction_in->tanggal_transaksi = $request->input('transaction_in_date');
$transaction_in->save();
$transaction_in->update(['idTransaction_in' => sprintf('TIN-%04d', $transaction_in->id)]);
$lastid=Transaction_in::create($transaction_in)->idTransaction_in;
if(count($request->device_type_name)>0){
foreach ($request->device_type_name as $item => $v) {
$data2=array(
'Transaction_in_id' => $lastid,
'DeviceType_id' => $request->device_type_name[$item],
'DeviceBrand_id' => $request->device_brand_name[$item],
'spek_device' => $request->device_spec[$item],
'harga_device' => $request->price[$item],
'jumlah_device' => $request->amount[$item],
'total_harga_device' => $request->total_price[$item]
);
Transaction_in_detail::insert($data2);
}
}
return redirect('/transactionsin')->with('success', 'Transaction success');
}
DeviceType_id
和Devicebrand_id
是外键。
答案 0 :(得分:0)
据我所知,您在此行中遇到了问题
$lastid=Transaction_in::create($transaction_in)->idTransaction_in;
$transaction_in
是对象,并且create
方法要求传入array
。
如果其他所有方法都正确,则应该可以:
$lastid=Transaction_in::create($transaction_in->toArray())->idTransaction_in;
答案 1 :(得分:0)
您已经save
了数据,但也使用了create
。它将在您的数据库中创建重复的记录。
我会给你一个解决方案:
$transactionIn = Transaction_in::create([
'idTransaction_id' => '0',
'supplier_id' => $request->input('supplier_name') // why supplier name assigned supplier_id?
'tanggal_transaksi' => $request->input('transaction_in_date'),
]);
$transactionIn = tap($transaction_in)->update([
'idTransaction_in' => sprintf('TIN-%04d', $transactionIn->id)
]);
$lastId = $transactionIn->idTransaction_in;