您想帮我吗?我想输入多个值并存储在具有不同行的数据库中。例如:
在输入表单中,
|project_id milestone_id|
| 1 1,2,3 |
| 2 2,4 |
我在数据库中的预期结果
|project_id milestone_id|
| 1 1 |
| 1 2 |
| 1 3 |
| 2 2 |
| 2 4 |
这是我的观点(tasktable \ projectmiles.blade.php)
<form action="{{route('project-miles.store')}}" method="post">
<label for="project" class="control-label mb-1">Project</label>
<div class="input-group col-lg-12">
<select name="project_id" id="project_id" class="form-control">
<option value="">Please Select</option>
@foreach ($projects as $item)
<option value="{{$item->id}}">{{$item->value}} - {{$item->description}}</option>
@endforeach
</select>
</div>
<label for="milestone" class="control-label mb-1">Milestone</label>
<div class="input-group col-lg-12">
<select multiple="multiple" name="milestone_id" id="milestone_id" class="form-control">
<option value="">Please Select</option>
@foreach ($milestones as $item)
<option value="{{$item->id}}">{{$item->value}} - {{$item->description}}</option>
@endforeach
</select>
</div>
<button type="submit" class="btn btn-lg btn-info btn-block"></button>
</form>
这是我的控制器(ProjectMilestoneController.php),我从2个模型(Milestone和Project)中获取价值
class ProjectMilestoneController extends Controller
{
public function index()
{
$projects = Project::get();
$milestones = Milestone::get();
return view('takstable.projectmiles',['projects'=>$projects, 'milestones'=>$milestones]);
}
public function store(Request $request)
{
ProjectMilestone::create($request->all());
return redirect()->route('project-miles.index');
}
}
这是我的模型(ProjectMilestone.php)
class ProjectMilestone extends Model
{
protected $fillable = ['project_id','milestone_id'];
public function project()
{
return $this->belongsTo(Project::class,'project_id','id');
}
public function milestone()
{
return $this->belongsTo(Milestone::class,'milestone_id','id');
}
}
谢谢您
答案 0 :(得分:0)
实现这一目标的Eloquent
方法是
public function store(Request $request)
{
foreach($request->milestone_id as $milestone_id) {
ProjectMilestone::create([
'project_id' => $request->project_id,
'milestone_id' => $milestone_id
]);
}
return redirect()->route('project-miles.index');
}
但这会影响系统的效率,因为如果选择了n个里程碑,那么将有n个查询到数据库。
为了避免此问题。
public function store(Request $request)
{
$prject_milestone = collect();
foreach($request->milestone_id as $milestone_id) {
$project_milestones->push(
ProjectMilestone::make([
'project_id' => $request->project_id,
'milestone_id' => $miletone_id
])
);
}
DB::table('project_milestones')->insert($project_milestones);
return redirect()->route('project-miles.index');
}
这只会对数据库执行一个查询。
由您选择
答案 1 :(得分:0)
您还必须在视图上创建数组。例如:
socket.read(integer)
请参阅@tharakaDilshan对于控制器的回答。