我对商店功能的一些小功能有一个问题,似乎我没有在互联网上找到任何适合我的答案。
我想在数组请求中添加静态数据,这样当发送数据时,在数据透视表中检查的字段将自动填充一些整数。
我有以下表格:
Schema::create('mounter_evaluations', function (Blueprint $table) {
$table->increments('id');
$table->integer('project_id')->index()->unsigned()->nullable();
$table->text('mentions')->nullable();
$table->softDeletes();
$table->timestamps();
});
Schema::create('mounter_procedures', function (Blueprint $table) {
$table->increments('id');
$table->integer('mounter_norm_id')->index()->unsigned()->nullable();
$table->string('detail');
$table->softDeletes();
$table->timestamps();
});
Schema::create('mounter_procedures_checks', function (Blueprint $table) {
$table->increments('id');
$table->integer('mounter_evaluation_id')->unsinged()->nullable()->index();
$table->integer('mounter_procedure_id')->unsinged()->nullable()->index();
$table->integer('checked')->unsinged()->nullable();
$table->timestamps();
});
以下型号:
public function mounterevaluation() {
return $this->belongsToMany(
'App\MounterEvaluation',
'mounter_procedures_checks',
'mounter_evaluation_id',
'mounter_procedure_id'
)->withPivot(['checked']);
}
public function mounterprocedures() {
return $this->belongsToMany(
'App\MounterProcedures',
'mounter_procedures_checks',
'mounter_evaluation_id',
'mounter_procedure_id'
)->withPivot(['checked']);
}
这是我的商店功能:
public function store(Request $request, $idProiect) {
$evaluation = MounterEvaluation::where('project_id', $idProiect)->first();
if (!$evaluation) {
$evaluation = new MounterEvaluation();
$evaluation->project_id = $idProiect;
}
$evaluation->mentions = $request->mentions;
$evaluation->save();
// $request->request->add(['checked' => 1]);
// $evaluation->mounterprocedures()->sync($request->procedures);
// $evaluation->mounterprocedures()->sync($request->all() + ['checked' => 1]);
$evaluation->mounterprocedures()->sync($request->procedures);
// $request->request->add(['checked' => 1]);
$evaluation->mounterprocedures()->request->add(['checked' => 1]);
return response()->json($evaluation, 201);
}
每当一个人在评估表中检查一些字段时,该检查将存储在数据透视表中。
将值放在$request
数组中的方法就像将值放在任何其他数组中一样:
$request['new_key1'] = 'new value 1';
$request['new_key2'] = 'new value 2';
以下是我知道它确实有效的方法,在你的控制器中,你有Request实例,作为参数传递,然后你可以像这样添加值:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
public function example(Request $request)
{
$request['new_key1'] = 'new value 1';
$request['new_key2'] = 'new value 2';
dd($request->input('new_key1'));//new value 1
}
在你的情况下,如果$request->procedures
是一个数组,那么你可以这样做:
$request->procedures = $request->procedures->toArray();
$request->procedures['checked'] = 1;
$evaluation->mounterprocedures()->sync($request->procedures);
我希望它有所帮助