【问题标题】:How to save a record with multiples foreing keys in Larave 8?如何在 Laravel 8 中保存具有多个外键的记录?
【发布时间】:2021-04-16 18:51:07
【问题描述】:

我有这些表:

vehicle_brands:

  • 身份证
  • 姓名

引擎:

  • 身份证
  • 姓名

车辆:

  • 身份证
  • 姓名
  • vehicle_brand_id
  • engine_id

车辆取决于vehicle_brands和engines,我想在保存车辆记录时保存vehicle_brands和engines id,我会这样做,但我认为这不是最好的方法

$vehicleBrand = VehicleBrand::find(1);

$engine = Engine::find(1);

$vehicle = Vehicle::create[(...)];

$vehicleBrand->vehicles()->save($vehicles);

$engine->vehicles()->save($vehicles);

【问题讨论】:

    标签: mysql laravel eloquent


    【解决方案1】:

    为什么不直接在创建时设置:

    $vehicle = Vehicle::create([
       "vehicle_brand_id" => 1,
       "engine_id" => 1
    ]);
    

    无需查找您已经知道 ID 的品牌和引擎。确保上面的值被标记为$fillable

    【讨论】:

    • 我正在努力消除技术债务,所以我认为应该有一种更简单、更好的方法来做到这一点。
    猜你喜欢
    • 1970-01-01
    • 2013-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-01
    • 2016-02-16
    • 2013-09-19
    • 1970-01-01
    相关资源
    最近更新 更多