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

标签: phplaraveleloquentbulkupdate

解决方案


推荐阅读