我正在嘗試在一個表中保存多個記錄(行)。html 欄位是動態欄位并宣告為陣列,因此它們可以是 1、2 或更多。
我的刀片:
<div class="col-md-12" id="inputFormRow" style="padding-left: 0px;">
<div class="input-group mb-3">
<input type="text" name="tableName[]" class="form-control m-input" placeholder="Name" autocomplete="off">
<input type="text" name="fromNr[]" class="form-control m-input" placeholder="From" autocomplete="off">
<input type="text" name="toNr[]" class="form-control m-input" placeholder="to" autocomplete="off">
<div class="input-group-append">
<button id="removeRow" type="button" class="btn btn-danger">X</button>
</div>
</div>
我的 JS 創建動態欄位:
$("#addRow").click(function () {
var html = '';
html = '<div id="inputFormRow" style="padding-left: 0px;">';
html = '<div >';
html = '<input type="text" name="tableName[]" placeholder="Name" autocomplete="off">';
html = '<input type="text" name="fromNr[]" laceholder="From" autocomplete="off">';
html = '<input type="text" name="toNr[]" placeholder="To" autocomplete="off">';
html = '<div >';
html = '<button id="removeRow" type="button" >X</button>';
html = '</div>';
html = '</div>';
$('#newRow').append(html);
});
我的 Offer.php 模型:
protected $fillable = ['some columns];
public function table()
{
return $this->hasMany(Table::class);
}
我的 Table.php 模型:
protected $fillable = ['offer_id','tableName','fromNr','toNr'];
public function offer()
{
return $this->hasMany(Offer::class);
}
現在,在我的控制器中,我必須獲取請求輸入值,然后保存到表中。輸入值可以大于 1 并且是動態的。
我的嘗試:
public function store(Request $request)
{
$statement = DB::select("SHOW TABLE STATUS LIKE 'offer'");
$nextId = $statement[0]->Auto_increment;
$tableName = $request->get('tableName');
$fromNr = $request->get('fromNr');
$toNr = $request->get('toNr');
$offer = Offer::find($nextId);
$offer->table()->saveMany([
new Table(['restaurant_offer_id' => $nextId]),
new Table(['tableName' => $tableName]),
new Table(['fromNr' => $fromNr]),
new Table(['toNr' => $toNr]),
]);
}
先感謝您。
uj5u.com熱心網友回復:
如果要使其動態化,則必須遍歷輸入陣列。
$tables = [];
foreach($tableName as $key => $value) {
$table = new Table;
$table->tableName = $tableName[$key];
$table->fromNr = $fromNr[$key];
$table->toNr = $toNr[$key];
$tables[] = $table;
}
$offer->table()->saveMany($tables);
uj5u.com熱心網友回復:
如果您name="example[]" 在視圖上使用,您將在控制器中接收變數作為陣列。此外,如果您使用 Eloquent 模型系結,您可以使用更簡單的語法將模型實體保存到資料庫中。
在控制器中嘗試這樣的事情:
public function store(Request $request)
{
foreach($request->tableName as $key => $tableName)
{
Offer::create(['tableName' => $tableName',
'fromNr' => $request->fromNr[$key],
'toNr' => $request->toNr[$key]])
}
}
此外,我建議在陣列的情況下使用復數命名。像 tableNames,fromNrs。所以你知道它應該包含多個變數。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/422698.html
標籤:
