[英]Laravel insert multiple records in pivot table from arrays
我正在嘗試在一個表中保存多個記錄(行)。 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 創建動態字段:
protected $fillable = ['some columns];
public function table()
{
return $this->hasMany(Table::class);
}
我的報價。php Model:
protected $fillable = ['offer_id','tableName','fromNr','toNr'];
public function offer()
{
return $this->hasMany(Offer::class);
}
我的表.php Model:
protected $fillable = ['offer_id','tableName','fromNr','toNr']; public function offer() { return $this->hasMany(Offer::class); }
現在,在我的 Controller 中,我必須獲取請求輸入值,然后保存到表中。 輸入值可以大於 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]), ]); }
先感謝您。
如果您在視圖上使用name="example[]"
,您將在 controller 中以數組形式接收變量。 此外,如果您使用 Eloquent Model 綁定,您可以使用更簡單的語法將 model 實例保存到數據庫中。
在 controller 中嘗試這樣的操作:
public function store(Request $request)
{
foreach($request->tableName as $key => $tableName)
{
Offer::create(['tableName' => $tableName',
'fromNr' => $request->fromNr[$key],
'toNr' => $request->toNr[$key]])
}
}
此外,我建議在 arrays 的情況下使用復數命名。 像 tableNames,fromNrs。 所以你知道它應該包含多個變量。
如果要使其動態化,則必須遍歷輸入數組。
$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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.