Laravel 5: syncing an extra field via pivot(Laravel 5:通过枢轴同步额外的字段)
问题描述
User model:
public function positions()
{
return $this->belongsToMany('AppPosition')->withPivot('company_id')->withTimestamps();
}
Positions model:
public function users()
{
return $this->belongsToMany('AppUser')->withPivot('company_id')->withTimestamps();
}
On form submission I have two arrays:
$allPositionIds
array:3 [
0 => 98
1 => 99
2 => 100
]
$allCompanyIds
array:3 [
0 => 129
1 => 130
2 => 131
]
Using
$user->positions()->sync($allPositionIds);
that syncs the position_user table as expected with the user and corresponding position ids.
However I can't work out how to populate the extra field ('company_id')
This is kind of what I would expect to work:
$user->positions()->sync([$allPositionIds => ['company_id' => $allCompanyIds]], false);
I have read the manual but I am just not seeing how to handle these arrays as the examples in the manual seem to relate to a situation where the extra field to be populated is not an array of multiple items:
$user->roles()->sync(array(1 => array('expires' => true)));
I have tried using this answer
to combine the two arrays:
$syncData = array_combine($allPositionIds,$allCompanyIds);
and get $syncData of :
array:3 [
98 => 129
99 => 130
100 => 131
]
Which maps accordingly to position id array and company id array but if I try
user->positions()->sync($syncData);
I get a "SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails" - I believe it is trying to add in the company_id as another position_user.position_id but then it errors out as that doesn't exist in the positions table.
Whatever I am trying at the moment my company_id
field is still not being updated/populated.
What am I doing wrong and how do I update that field?
You are actually pretty close. The required format is:
[
98 => ['company_id' => 129],
99 => ['company_id' => 130],
100 => ['company_id' => 131]
]
This should generate the correct array:
$extra = array_map(function($companyId){
return ['company_id' => $companyId];
}, $allCompanyIds);
$data = array_combine($allPositionIds, $extra);
$user->positions()->sync($data);
这篇关于Laravel 5:通过枢轴同步额外的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Laravel 5:通过枢轴同步额外的字段
基础教程推荐
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01
- 超薄框架REST服务两次获得输出 2022-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- 在多维数组中查找最大值 2021-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01