首页 文章

从Laravel Eloquent集合中取消/删除关系对象

提问于
浏览
0

我通过以下方式获取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);

任何帮助将不胜感激 .

提前致谢

2 回答

  • 3

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

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

    在那之前:

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

    我必须使用相同字段的表 . 所以我需要根据值检查不同的列 . 因此,如果外键的值相同,则需要取消设置该关系

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

相关问题