Laravel 5.1在热切加载时更新模型关系不要坚持使用数据库

时间:2015-07-16 20:11:43

标签: mysql laravel eloquent laravel-5 laravel-5.1

我正在更新属于某个位置的租借,我可以填写并保留租赁数据,但是当我填写通过急切加载检索的位置关系数据时,如果我尝试save(),update(),或推();它不会持久存储到数据库中。根据文档,push()应该起作用,因为它显然会持续存在关系。

更新操作

public function update($id, RentalUpdateRequest $request)
{
    // Eager load the rental with relationships
    $Rental = Rental::with('location')->find($id);

    // Retrieve rental data from request, and fill
    $requestData = $request->only('stall', 'level', 'description');
    $Rental->fill($requestData);

    // Retrieve rental location data from request, and fill
    $requestData = $request->only(
        'location.street_address',
        'location.city',
        'location.province',
        'location.country',
        'location.postal_code'
    );
    $Rental->location->fill($requestData);

    // Persist rental to database, as well as all relationships
    $Rental->update();

    // Return rental data for capture by AngularJS interceptor
    return response()->json([
        'rental' => $Rental,
        'action' => 'rental_updated',
        'message' => trans('rental.updated')
    ]);
}

Payload和Eager Loaded Data以相同方式格式化

客户端装载的原始租赁

rental: 
    description: "This is a rental."
    id: 1
    level: "7"
    location: 
        city: "Victoria"
        country: "Canada"
        id: 11
        postal_code: "V8T 2L5"
        province: "British Columbia"
        street_address: "180 Blanshard Dr."
    region_id: 1
    rental_location_id: 11
    stall: "7"
    user_id: 1

如果有效负载是:

rental: 
    description: "This is a rental."
    id: 1
    level: "9" <-- Changed
    location: 
        city: "asdf" <-- Changed
        country: "asdf" <-- Changed
        id: 11
        postal_code: "V8T 2L5"
        province: "asdf" <-- Changed
        street_address: "180 Blanshard Dr."
    region_id: 1
    rental_location_id: 11
    stall: "7"
    user_id: 1

Save(),Update()或Push()之后的响应

rental: 
    description: "This is a rental."
    id: 1
    level: "9" <-- Persisted
    location: 
        city: "Victoria" <-- NOT Persisted
        country: "Canada" <-- NOT Persisted
        id: 11
        postal_code: "V8T 2L5"
        province: "British Columbia" <-- NOT Persisted
        street_address: "180 Blanshard Dr."
    region_id: 1
    rental_location_id: 11
    stall: "7"
    user_id: 1

看来在Laravel 5.1中,push()正在从API中删除,不再在5.1文档中,但是save()和update()也没有任何建议吗?

我现在已经多次遇到这种情况,我尝试设置一个急切加载的关系的属性,但只有顶级键:值对持久存在,而子关系对不是。解决这个问题的唯一方法就是单独获取位置并保存(),但是如果我不能保存关系,那么急切加载的重点是什么,并且必须向DB发出另一个请求。 / p>

0 个答案:

没有答案