Laravel:与数组的额外字段同步
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28903692/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel: extra field sync with array
提问by kazehaya
Im trying to save data inside a pivot table with an extra field called data.
我试图将数据保存在一个名为 data 的额外字段的数据透视表中。
when i save i have this array:
当我保存时,我有这个数组:
[
5 => "files"
4 => "pictures"
3 => "tags"
1 => "thumbs"
]
My table looks like this:
我的桌子看起来像这样:
- project_id
- option_id
- name
- 项目编号
- option_id
- 姓名
The ids shown above refer to option_id and the string to name inside the database.
上面显示的 id 指的是 option_id 和要在数据库中命名的字符串。
When i try to use sync like this: $project->options()->sync($data);
当我尝试像这样使用同步时: $project->options()->sync($data);
$data is the array shown above
$data 是上面显示的数组
Im getting a error thats its trying to save the option_id with "files".
我收到一个错误,那就是它试图用“文件”保存 option_id。
Here is how i build up the data that i use for sync:
以下是我建立用于同步的数据的方法:
Im trying to get what you suggested but dont know how to achieve it:
我试图得到你的建议,但不知道如何实现它:
here is how i build up the array:
这是我建立阵列的方式:
foreach($request->input('option_id') as $id) {
$option['option_id'][] = $id;
$option['data'][] = $request->input('data')[$id];
}
$data = array_combine($option['option_id'], $option['data']);
回答by Jeff Lambert
This is covered in the manual:
这在手册中有介绍:
Adding Pivot Data When Syncing
You may also associate other pivot table values with the given IDs:
$user->roles()->sync(array(1 => array('expires' => true)));
同步时添加枢轴数据
您还可以将其他数据透视表值与给定的 ID 相关联:
$user->roles()->sync(array(1 => array('expires' => true)));
In your example, you would have to change your array to look something like below but I believe this would translate to:
在您的示例中,您必须将数组更改为如下所示,但我相信这会转化为:
$data = [
5 => [ 'name' => "files" ],
4 => [ 'name' => "pictures" ],
3 => [ 'name' => "tags" ],
1 => [ 'name' => "thumbs" ],
];
$project->options()->sync($data);
I believe you may also need to modify how your Project
model relates itself to your Options
model:
我相信您可能还需要修改Project
模型与模型的关联方式Options
:
// File: app/model/Project.php
public function options()
{
return $this->belongsToMany('Option')->withPivot('name');
}
This is also noted in the linked-to manual page:
这也在链接到的手册页中注明:
By default, only the keys will be present on the pivot object. If your pivot table contains extra attributes, you must specify them when defining the relationship.
默认情况下,只有键会出现在枢轴对象上。如果数据透视表包含额外的属性,则必须在定义关系时指定它们。
Update
更新
Try creating your $data
array like this:
尝试$data
像这样创建数组:
$data = [];
foreach($request->input('option_id') as $id) {
$data[$id] = [ 'name' => $request->input('data')[$id] ];
}