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

vfwfrxfs  于 6个月前  发布在  其他
关注(0)|答案(4)|浏览(86)

我有一个获取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);


任何帮助将不胜感激。
Thanks in advance

xlpyo6sf

xlpyo6sf1#

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

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

字符串
在此之前:

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

rt4zxlrg

rt4zxlrg2#

你可以取消设置

unset($product->merchant);

字符串

af7jpaap

af7jpaap3#

我必须与相同的字段表。.所以我需要检查不同的列的基础上的价值.所以,如果值的外键是相同的,然后需要取消这种关系
如果模型中有merchant属性(表中的merchant列),则可以使用$product->getOriginal('merchant')$product->getAttribute('merchant')获取其值

xj3cbfub

xj3cbfub4#

withoutEagerLoads()

字符串
为我工作在这里是一个例子:

$observations = Observation::selectRaw('COUNT(*) as count, DATE(created_at) as date')
        ->whereIn('tenant_id', $tenant_ids)
        ->whereBetween('created_at', $timelines[$request->timeline])
        ->groupBy('date')
        ->withoutEagerLoads()
        ->get();

相关问题