php - LARAVEL Eloquent: BelongsTo 关系 - 批量更新
问题描述
想象一下,我想将多本书借给客户。
一个客户可以借出多本书(hasMany),但一本书只能借给一个客户(BelongsTo)。我想一次性更改多本书的关系的 BelongsTo 方面。 Laravel 文档说要使用 associate() 函数。但据我所知,这是一次更改一个对象。所以我必须像 massLoanOne 那样使用循环。这会产生很多查询 (n + 1)。
另一种方法是直接更新 Book 模型上的 customer_id,如在 massLoanTwo 中。这仅生成 2 个查询。但这不是正确的面向对象方式。
有没有更好的方法来使用 Eloquent 魔法更新这种一对多(反向)关系 bij 的 BelongsTo 方面?
<?php
public function massLoanOne(MassLoanCustomerRequest $request)
{
foreach ($request->ids as $id) {
Book::find($id)->customer()->associate(Customer::find($request->customer_id))->save();
}
return response()->noContent();
}
public function massLoanTwo(MassLoanCustomerRequest $request)
{
Book::whereIn('id', request('ids'))->update(['customer_id' => $request->customer_id]);
return response()->noContent();
}
?>
解决方案
推荐阅读
- node.js - npm install 包名连接到 127.0.0.1:3000
- soap - 如何在 Erlang 中使用设置的 http_header 发送请求 打包一个 SOAP github 包
- c# - 在另一个类中更改 ViewModel 属性不会更新 UI
- php - Laravel 雄辩的一对多关系
- angular - 旋转变压器角 5 有什么好处
- python - 魔杖创建空帧和不规则帧速率
- python - opencv中的图像处理
- java - 如何缓存 Map 等复杂对象
> 在 Spring Boot 应用程序中 - windows-10 - Windows 10 上的 NetLogo 问题
- three.js - Three.js:玻璃材质故障