【问题标题】:Unset/Remove relation object from Laravel Eloquent collection从 Laravel Eloquent 集合中取消设置/删除关系对象
【发布时间】:2019-02-16 02:07:41
【问题描述】:

我通过以下方式获取 Laravel Eloquent 集合:

$product = Product::query()->with(['merchant', 'picture'])->where('id', $id)->first();

得到$product的转储是

Product {
  #casts: ...
  #dates: ...
  #connection: "mysql"
  #table: null
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #attributes: array:1 [
    "id" => 27
  ]
  #original: ...
  #changes: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: array:2 [
    "merchant" => Merchant {...}
    "picture" => Picture {...}
    }
  ]
  #touches: []
  +timestamps: true
  #hidden: []
  #visible: []
  #fillable: []
  #guarded: ...
}

我需要从这个集合中取消设置关系对象merchantpicture

我尝试了以下选项但失败了:

unset($product['merchant']);
unset($product->merchant);

任何帮助将不胜感激。

提前致谢

【问题讨论】:

  • 你解除这些关系的目的是什么?
  • 我必须拥有相同字段的表。所以我需要根据值检查不同的列。因此,如果外键的值相同,则需要取消设置该关系
  • 您有哪些具有相同字段的表?请举个例子好吗?
  • $product->merchant = null 怎么样?
  • 如果我不想要价值,那应该可以。但我需要取消设置密钥。

标签: laravel eloquent


【解决方案1】:

我必须使用相同字段的表。所以我需要检查 基于值的不同列。所以如果外键的值为 同样需要取消该关系

如果模型中有merchant 属性(表中的merchant 列),则可以使用$product->getOriginal('merchant')$product->getAttribute('merchant') 获取它的值

【讨论】:

    【解决方案2】:

    在 Laravel 5.6.25 中,你可以使用unsetRelation():

    $product->unsetRelation('merchant')->unsetRelation('picture');
    

    在那之前:

    $relations = $product->getRelations();
    unset($relations['merchant'], $relations['picture']);
    $product->setRelations($relations);
    

    【讨论】:

    • 工作就像一个魅力!谢谢
    【解决方案3】:

    你可以取消设置

    unset($product->merchant);
    

    【讨论】:

    • 你读过这个问题吗? "我尝试了以下选项但失败了:unset($product['merchant']); unset($product->merchant);"
    • 它到底是怎么不适合你的?有没有错误?
    猜你喜欢
    • 2022-11-04
    • 2021-07-10
    • 2015-05-14
    • 1970-01-01
    • 2020-09-09
    • 2021-07-15
    • 2014-01-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多