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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/52278128/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 18:02:46  来源:igfitidea点击:

Unset/Remove relation object from Laravel Eloquent collection

laraveleloquent

提问by Ajay Makwana

I've a fetch a Laravel Eloquent collection by:

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

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

and get the dump of $productis

并得到转储$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: ...
}

I need to unset the relation object merchantand picturefrom this collection.

我需要取消的关系对象merchant,并picture从这个集合。

I've tried following options but failed:

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

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

Any help will be appreciate.

任何帮助将不胜感激。

Thanks in advance

提前致谢

回答by Jonas Staudenmeir

In Laravel 5.6.25, you can use unsetRelation():

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

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

Before that:

在那之前:

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

回答by Andrey Lutskevich

I have to tables with the same fields.. So I need to check the different column based on value. So if the value of foreign key is same then need to unset that relation

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

If you have merchantproperty in the model (merchantcolumn in the table) you can get it value using $product->getOriginal('merchant')or $product->getAttribute('merchant')

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

回答by Yevgeniy Afanasyev

you can unset it

你可以取消设置

unset($product->merchant);