【问题标题】:How to update a child table with parent model?如何使用父模型更新子表?
【发布时间】:2020-12-04 00:57:59
【问题描述】:

我有 2 个表 productsvariants,具有 hasMany 关系,结构如下:

产品表

|     id          name            image          manufacturer
|     1           T-Shirt         t-s.jpg        docomo      
|     2           Short Skirt     s-skirt.jpg    docomo  

变量表

|     id     product_id      name       price    sku       quantity
|     1         1             S          30      ts-s       100
|     2         1             M          32      ts-m       100
|     3         1             XL         35      ts-xl      100
|     4         2             S          23      sk-s       100
|     5         2             M          25      sk-m       100
|     6         2             XL         28      sk-xl      100

产品型号

public function variants()
{
   return $this->hasMany(Variant::class);
}

变体模型

public function product()
{
   return $this->belongsTo(Product::class);
}

我可以使用 Product 模型将数据保存在 Variant(子表)上,但问题是,我无法使用 Product 更新 Variant 表,我该如何更新有父的子模型???

【问题讨论】:

  • 你能分享一下让你遇到问题的代码吗?

标签: laravel eloquent laravel-6


【解决方案1】:
// Single Update
$variant = Variant::find($variantId)->fill($requestData)->save();
$variant->product()->fill(['name'=>'abc','price'=>'20'])->save();

// Multiple Update/Store
$variant = null;

foreach ($requestVariants as $requestVariant) {
    if ($variant = Variant::find($requestVariant['id'] ?? null)) {
        $variant->fill($requestData)->save();
    } else {
        $variant = Variant::create($requestData);
    }
}

if ($variant) {
    $variant->product()->fill(['name'=>'abc','price'=>'20'])->save();
}

也许它可以这样工作

【讨论】:

    【解决方案2】:

    你可以试试这个

    $product=Product::find($id);
    $product->variants()->update(['name'=>'abc','price'=>'20']);
    

    希望对你有用

    【讨论】:

      猜你喜欢
      • 2013-08-26
      • 2021-04-25
      • 2014-01-11
      • 2011-09-20
      • 2016-03-20
      • 2017-06-06
      • 2021-10-02
      • 1970-01-01
      • 2017-05-30
      相关资源
      最近更新 更多