我有两张桌子car_category和车辆并将车辆ID设置为车辆表c_id的外键约束。现在我想将车辆添加到车辆表格中。所以我想存储车辆细节,怎么样我将fk约束添加到我的控制器? 我已经设置了表格之间的关系, 在汽车模型中,
class car extends Model
{
protected $guarded = [];
protected $table = 'car_category';
public function vehicles()
{
return $this->hasMany('Vehicle');
}
}
车型,
class Vehicle extends Model
{
protected $guarded = [];
protected $table = 'vehicles';
public function cars()
{
return $this->belongsTo('Car');
}
}
并存储车辆详细信息,
public function store(Request $request)
{
$this->validate($request, [
'vehicle_no' => 'required',
'vehicle_company' => 'required',
'vehicle_category' => 'required',
'vehicle_type' => 'required',
'vehicle_model' => 'required',
'vehicle_capacity' => 'required',
'vehicle_color' => 'required',
'c_cid' => '',
]);
Vehicle::create($request->all());
return redirect()->route('vehicles.index')
->with('success','Vehicle details stored successfully');
}
如何传递fk约束值?有人可以帮助我吗?
答案 0 :(得分:0)
尝试在您的表单中添加汽车字段,您可以在保存车辆时获取ID
<div class="col-md-6">
<select name="c_id" class="form-control">
@foreach($car as $cars)
<option value="{{ $cars->id }}">{{ $cars->Name }}</option>
@endforeach </select>
</div>
这里你可以获得
中的值public function store(Request $request) {
// here you can get the value
$request->c_id;
}