从 Laravel Eloquent 集合中取消设置/删除关系对象 [英] Unset/Remove relation object from Laravel Eloquent collection

查看:25
本文介绍了从 Laravel Eloquent 集合中取消设置/删除关系对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've a fetch a Laravel Eloquent collection by:

$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.

I need to unset the relation object merchant and picture from this collection.

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

I've tried following options but failed:

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

任何帮助将不胜感激.

提前致谢

推荐答案

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

In Laravel 5.6.25, you can use unsetRelation():

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

在那之前:

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

这篇关于从 Laravel Eloquent 集合中取消设置/删除关系对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆