简体   繁体   English

Laravel插入具有一对多关系的记录

[英]Laravel insert record with one to many relationship

I have two tables car_category and vehicles and set the car Id as foreign key constraint of vehicles table's c_id.Now I want to add vehicles to vehicles table with the relationship.So I want to store the vehicle details,How 'ld I add the fk constraint to my controller? 我有两个表car_category和Vehicles,并将car ID设置为Vehicles表的c_id的外键约束。现在我想将车辆添加到带有关系的Vehicles表中。因此,我想存储车辆详细信息,请问我如何添加fk约束我的控制器? I've set the relationship between tables like, In Car model, 我已经设置了表格之间的关系,例如车载模型,

class car extends Model
{
    protected $guarded = [];
    protected $table = 'car_category';

    public function vehicles()
    {
        return $this->hasMany('Vehicle');
    }
}

Vehicle Model, 车辆型号

class Vehicle extends Model
{
    protected $guarded = [];
    protected $table = 'vehicles';

    public function cars()
    {
        return $this->belongsTo('Car');
    }
}

And store vehicle details like, 并存储车辆详细信息,例如

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');
}

How to pass the fk constraint value?Can anybody help me? 如何传递fk约束值?有人可以帮助我吗?

Try adding the car field in you form, you can get the ID while saving the vehicle 尝试在表格中添加汽车字段,您可以在保存车辆的同时获取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>

here you can get the value in 在这里你可以得到价值

public function store(Request $request) {
    // here you can get the value
    $request->c_id;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM