laravel - Laravel 中的 attach() 方法有什么用?
问题描述
我不知道这种方法有什么用,我在类似这样的代码上看到了一些东西。
$user = JWTAuth::parseToken()->authenticate();
$new_car = new Car();
$new_car->name = $request->name;
$new_car->age = $request->age;
$new_car->model = $request->model;
$new_car->save();
$time = new Reservation();
$time->from_date = $request->from_date;
$time->to_date = $request->to_date;
$time->from_time= $request->from_time;
$time->to_time = $request->to_time;
$time->save();
// Attach the reservation to the car's reservations
$new_car->Reservation()->attach($time->id);
// Attach the car to the user cars
$user->cars()->attach($new_car->id);
希望有人能很好地解释我。
解决方案
连接/分离
Attach 主要用于多对多关系中的雄辩关系。它主要使用中间表数据插入或更新。例如,假设一个用户可以有很多角色,而一个角色可以有很多用户。您可以使用 attach 方法通过在关系的中间表中插入一条记录来将角色附加到用户:
推荐阅读
- git - 从 GitLab 到 GitHub 的 Git 合并分支
- windows - 无法在 Windows 10 上将模型链接到“en_core_web_md”
- python - 基数为 10 的 int() 的无效文字:“冰淇淋”错误
- solr - Delta 导入导致 Solr 响应翻倍甚至更差
- perl - Perl Redis 监听不订阅频道
- powershell - 如何使用 PowerShell 更改 Chrome 中的默认下载文件夹?
- c - 为什么这段代码开头需要分号
- apache-spark - Spark 依赖较少的模型导出如何工作?
- java - 从 jdk 8 迁移到 11,得到空字符串,之前是普通字符串
- angular - 创建组件实例并作为 [object HTMLelement] 传递给另一个组件