我有一個(gè)用于存儲(chǔ)特定藝術(shù)家的記錄數(shù)據(jù)的表單頁(yè)面。大多數(shù)數(shù)據(jù)屬于記錄表,但有些數(shù)據(jù)應(yīng)該存儲(chǔ)在相關(guān)表中。我現(xiàn)在主要關(guān)心的是流派表。在流派表中,我有 Name 列。我對(duì)表單提交后的理想流程的想法是:檢查流派名稱(chēng)是否已存在如果不是:存儲(chǔ)名稱(chēng)并將其 id 用作 fk如果是:獲取流派 id 并將其用作 fk我正在處理的是 Recording 控制器中的 store 方法。目前我正在使用錄音表中的 $recording_date、$release_date 和 $lyrics。免責(zé)聲明:我不會(huì)向您展示我嘗試過(guò)的大部分內(nèi)容,因?yàn)闊o(wú)法向您展示我嘗試過(guò)的所有方式,而且它也是無(wú)用的,因?yàn)閱?wèn)題不在于我不明白為什么它不起作用。我根本找不到任何方法來(lái)正確使用包含相同約束和一對(duì)多關(guān)系的 Eloquent。大多數(shù)人會(huì)建議我以單獨(dú)的形式進(jìn)行。另外我知道我現(xiàn)在沒(méi)有處理驗(yàn)證。無(wú)論如何,我可以找到適用于我的類(lèi)似案例信息的任何想法或建議都會(huì)有所幫助。<!--Form snippet--><div class="form-group"> <div class="input-group"> <input type="text" name="genre" class="form-control" placeholder="Genre" autocomplete="off"> </div></div>以下是我嘗試過(guò)的最新代碼。它不起作用的明顯原因是它不處理外鍵。//Recording controllerpublic function store(Request $request) { $genre = new Genre(); $genre->name = $request->input('genre'); $recording = new Recording(); $recording->genre_id = $genre->id; $recording->recording_date = $request->input('recording_date'); $recording->release_date = $request->input('release_date'); $recording->lyrics = $request->input('lyrics'); $recording->save(); }//Recording tablepublic function up() public function up() { Schema::create('recordings', function (Blueprint $table) { $table->bigIncrements('id'); $table->unsignedInteger('genre_id')->nullable(); $table->string('recording_date')->nullable(); $table->string('release_date')->nullable(); $table->text('lyrics')->nullable(); $table->timestamps(); }); }//Genres table public function up() { Schema::create('genres', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('name')->unique()->nullable(); $table->string('subgenre')->nullable(); $table->timestamps(); }); }//Recording modelclass Recording extends Model{ protected $guarded = []; public function genre() { return $this->belongsTo(Genre::class); }}
2 回答

一只名叫tom的貓
TA貢獻(xiàn)1906條經(jīng)驗(yàn) 獲得超3個(gè)贊
為了保存到關(guān)系表中,您必須執(zhí)行以下操作:
$recording->genre()->create('your data array here')
你可以在這里閱讀更多關(guān)于它的信息。
現(xiàn)在,如果您想檢查 $recording 是否具有類(lèi)型,您可以首先使用 exists() ,例如:
$recording->genre()->exists()
另一種選擇是使用方法 firstOrCreate、firstOrNew,您可以在此處閱讀有關(guān)它們的更多信息。

牛魔王的故事
TA貢獻(xiàn)1830條經(jīng)驗(yàn) 獲得超3個(gè)贊
請(qǐng)?jiān)囋囘@個(gè)
....
$genre->save();
$genre->recordings()->create([
"recording_date"=>$request->input('recording_date'),
"release_date"=>$request->input('release_date'),
"lyrics"=>$request->input('lyrics')
]);
- 2 回答
- 0 關(guān)注
- 162 瀏覽
添加回答
舉報(bào)
0/150
提交
取消