从 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
Unset/Remove relation object from Laravel Eloquent collection
提问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 $product
is
并得到转储$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 merchant
and picture
from 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 merchant
property in the model (merchant
column 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);