【问题标题】:Laravel pivot sync() attaches wrong valuesLaravel pivot sync() 附加了错误的值
【发布时间】:2018-08-11 23:49:39
【问题描述】:

我几乎在每一个到数据透视表的 sync() 上都处理过这个问题,在 Laravel 5.6 中,当我执行以下操作时,它会添加请求中不存在的一行:

$firm_data = request()->all(); // get the request data
$firm = Firm::where('id', request('firm_id')); // get the Firm model
$firm->update($firm_data); // update the model

// add the firm address with a belongsToMany() relationship set on Models\Firm and on Models\Address
$address = $firm->with('addresses')->first();
$addresses = request('addresses'); // get the request data for address
$address->update($addresses); // all ok till here

// deal with the pivot table
// here's the issue...
$address->cities()->sync([request('firm_id'), $addresses['city_id']]); 

公司数据和地址数据状态已正确保存在数据库中,尽管数据透视表填充了两列而不是一列。

在整个请求中,我只有一个city_id = 3034856,但将它添加到数据透视表的第一行firm_id = 1,city_id = 1,“不知从何而来”:

数据透视表 - Firm_city

+---------+---------+ | firm_id | city_id | +---------+---------+ | 1 | 1 | | 1 | 3034856 | +---------+---------+

对为什么会发生这种情况有任何想法吗?

只是为了确保它是正确的,这里是每个模型公司和地址的方法:

// On the Firm model
public function cities()
{
    return $this->belongsToMany(City::class, 'firm_city');
}

// on the City model
public function firms()
{
    $this->belongsToMany(Firm::class, 'firm_city');
}

提前感谢您对为什么会发生这种情况的任何见解,

【问题讨论】:

    标签: laravel eloquent many-to-many pivot-table


    【解决方案1】:

    删除firm_id:

    $address->cities()->sync([$addresses['city_id']]);
    

    Eloquent 从$address 获取firm_id,您不必指定它。
    如果您指定 它,Eloquent 假设您想将 Cityid=1 同步。

    【讨论】:

    • 非常感谢乔纳斯的回答和编辑。它现在工作正常。我对此越来越疯狂。谢谢! :)
    猜你喜欢
    • 2015-08-03
    • 1970-01-01
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多