首页 > 解决方案 > 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);

希望有人能很好地解释我。

标签: laraveleloquentlaravel-collection

解决方案


连接/分离

Attach 主要用于多对多关系中的雄辩关系。它主要使用中间表数据插入或更新。例如,假设一个用户可以有很多角色,而一个角色可以有很多用户。您可以使用 attach 方法通过在关系的中间表中插入一条记录来将角色附加到用户:

更多细节


推荐阅读