【发布时间】:2022-01-17 11:11:04
【问题描述】:
你能帮帮我吗,对不起,我是 laravel 的新手。我想从 table master 获取 ID,但我只能将 id 发送到 URL,我不知道如何获取该 id 以保存在 table 详细信息中。
我有两张表,下面是第一张表(master):
public function up()
{
Schema::create('landings', function (Blueprint $table) {
$table->id();
$table->string('title')->nullable();
$table->text('content')->nullable();
$table->text('photo')->nullable();
$table->timestamps();
});
}
那么下面是第二张表(详细):
public function up()
{
Schema::create('landingmetas', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('landing_id');
$table->foreign('landing_id')->references('id')->on('landings')->onDelete('cascade')->onUpdate('cascade');
$table->string('meta_key')->unique();
$table->string('meta_value')->nullable();
$table->timestamps();
});
}
这是我的控制器,用于将数据保存在着陆表中并完美运行:
public function store(Request $request)
{
$landings = new Landing();
$landings->title = $request->title;
$landings->save();
Session::flash('landing-add','Section telah dibuat.');
return redirect()->route('landing.createlm', $landings->id);
}
正如你在这一行中看到的return redirect()->route('landing.createlm', $landings->id); 我重定向到landing.createlm.blade.php(输入数据到第二个表的表单)。那时仍然可以按我的意愿工作,但是我很难将数据输入到landingmetas,因为我不知道如何获取该url ID。这是我的控制器,用于将数据存储到landingmetas(明细表):
public function storelm(Request $request)
{
$lm = new Landingmeta();
$meta_key = strtolower($request->meta_key);
$meta_key = str_replace(" ", "", $meta_key);
$lm->meta_key = substr($meta_key, 0, 3)."-".substr($meta_key, 3);
$lm->landing_id = ???? (here id from master table)
$lm->save();
Session::flash('add-field','Field telah ditambahkan.');
return back();
}
这是我的路线:
/*Landing page*/
Route::get('/landings', [App\Http\Controllers\LandingController::class, 'index'])->name('landing.index');
Route::post('/landings', [App\Http\Controllers\LandingController::class, 'store'])->name('landing.store');
Route::get('/landings/{landing}/create', [App\Http\Controllers\LandingController::class, 'edit'])->name('landing.edit');
Route::delete('/landings/{landing}/destroy', [App\Http\Controllers\LandingController::class, 'destroy'])->name('landing.destroy');
/*Create Landingmetas*/
Route::get('landings/{landing}/createfield', [App\Http\Controllers\LandingController::class, 'createlm'])->name('landing.createlm');
Route::post('/landinglm', [App\Http\Controllers\LandingController::class, 'storelm'])->name('landing.storelm');
【问题讨论】:
标签: laravel eloquent foreign-keys save