这是一个用于借用实验室设备的系统,在该系统中,用户必须先填写其个人数据,然后才能借用实验室设备。有一种由名称和地址组成的工具借出形式,将存储在“贷款设备” 表中,从“实验室设备” 表中选择一个工具列表,并且数据将以多对多方法存储在“贷款清单” 表中。
我有3张桌子 贷款设备表(ID,名称,地址), lab_equipment表(ID,名称), 贷款清单表(loan_equipment_id,lab_equipment_id,金额)
这是 LoanEquipment.php 模型:
public function labEquipment()
{
return $this->belongsToMany('App\LabEquipment', 'loan_lists', 'loan_equipment_id',
'lab_equipment_id')->withTimestamps();
}
这是 LabEquipment.php 模型:
public function loanEquipment()
{
return $this->hasMany('App\LoanEquipment');
}
这是 LoanEquipmentController.php 控制器:
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required|max:128',
'address' => 'required',
'labEquipment' => 'required'
]);
$input = LoanEquipment::create($request->all());
$input->labEquipment()->attach($request->input('labEquipment'));
Session::flash("flash_notification", [
"level" => "success",
"message" => "Success $input->name."
]);
return redirect()->route('loan.index');
}
这是用于填写贷款清单工具 form.blade.php 的视图或表单:
输入名称:
<div class="form-group {{ $errors->has('name') ? 'has-error' : '' }}">
{!! Form::label('name', 'Nama', ['class' => 'col-md-2 control-label']) !!}
<div class="col-md-6">
{!! Form::text('name', null, ['class' => 'form-control']) !!}
<strong>{!! $errors->first('name', '<p class="help-block">:message</p>') !!}</strong>
</div>
输入地址:
<div class="form-group {{ $errors->has('address') ? 'has-error' : '' }}">
{!! Form::label('address', 'Address', ['class' => 'col-md-2 control-label']) !!}
<div class="col-md-6">
{!! Form::text('address', null, ['class' => 'form-control']) !!}
<strong>{!! $errors->first('address', '<p class="help-block">:message</p>') !!}</strong>
</div>
选择并输入 labEquipment 和 amount
<div class="form-group {{ $errors->has('labEquipment') ? 'has-error' : '' }}">
{!! Form::label('labEquipment', 'Daftar Alat Laboratorium', ['class' => 'col-md-2 control-label']) !!}
<div class="col-md-6">
@if(count($listsLabEquipment) > 0)
@foreach($listsLabEquipment as $key => $value)
<div class="checkbox">
<label for="">{!! Form::checkbox('labEquipment[]', $key, null) !!}
{{ $value }}
</label>
</div>
{!! Form::text('amount', null, ['class' => 'form-control']) !!}
@endforeach
@endif
<strong>{!! $errors->first('labEquipment', '<p class="help-block">:message</p>') !!}</strong>
</div>
如何通过工具贷款表格添加或输入有关借入工具数量的数据?并以名称“ amount”存储在“ loan_lists”表中。我应该如何在控制器,模型和视图中编写代码?
谢谢您的帮助
答案 0 :(得分:0)
如果我正确理解,您需要在lab_equipment和loan_equipment之间建立多对多的关系。要定义多对多关系,您需要在两个模型中都添加一个属于多对关系。指的是laravel文档。 https://laravel.com/docs/5.7/eloquent-relationships#many-to-many。如果在列名和表名中使用自定义约定,则必须像在第一个关系声明中所做的那样,将它们作为关系声明中的参数传递。要访问数据透视表,您需要执行以下操作
public function labEquipment()
{
return $this->belongsToMany('App\LabEquipment', 'loan_lists', 'loan_equipment_id',
'lab_equipment_id')->withTimestamps()->withPivot('column1', 'column2');
}