Laravel: 额外字段与数组同步
Laravel: extra field sync with array
我正在尝试使用名为数据的额外字段将数据保存在数据透视表 table 中。
当我保存时,我有这个数组:
[
5 => "files"
4 => "pictures"
3 => "tags"
1 => "thumbs"
]
我的 table 看起来像这样:
- project_id
- option_id
- 名字
上面显示的id是指option_id和数据库中要命名的字符串。
当我尝试像这样使用同步时:$project->options()->sync($data);
$data就是上面显示的数组
我在尝试用 "files" 保存 option_id 时遇到错误。
以下是我如何建立用于同步的数据:
我正在尝试获得您的建议,但不知道如何实现:
以下是我构建数组的方式:
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']);
这在 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)));
在您的示例中,您必须将数组更改为如下所示,但我相信这将转化为:
$data = [
5 => [ 'name' => "files" ],
4 => [ 'name' => "pictures" ],
3 => [ 'name' => "tags" ],
1 => [ 'name' => "thumbs" ],
];
$project->options()->sync($data);
我相信您可能还需要修改 Project
模型与 Options
模型的关联方式:
// File: app/model/Project.php
public function options()
{
return $this->belongsToMany('Option')->withPivot('name');
}
链接到的手册页中也指出了这一点:
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.
更新
尝试像这样创建 $data
数组:
$data = [];
foreach($request->input('option_id') as $id) {
$data[$id] = [ 'name' => $request->input('data')[$id] ];
}
我正在尝试使用名为数据的额外字段将数据保存在数据透视表 table 中。
当我保存时,我有这个数组:
[
5 => "files"
4 => "pictures"
3 => "tags"
1 => "thumbs"
]
我的 table 看起来像这样:
- project_id
- option_id
- 名字
上面显示的id是指option_id和数据库中要命名的字符串。
当我尝试像这样使用同步时:$project->options()->sync($data);
$data就是上面显示的数组
我在尝试用 "files" 保存 option_id 时遇到错误。
以下是我如何建立用于同步的数据:
我正在尝试获得您的建议,但不知道如何实现:
以下是我构建数组的方式:
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']);
这在 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)));
在您的示例中,您必须将数组更改为如下所示,但我相信这将转化为:
$data = [
5 => [ 'name' => "files" ],
4 => [ 'name' => "pictures" ],
3 => [ 'name' => "tags" ],
1 => [ 'name' => "thumbs" ],
];
$project->options()->sync($data);
我相信您可能还需要修改 Project
模型与 Options
模型的关联方式:
// File: app/model/Project.php
public function options()
{
return $this->belongsToMany('Option')->withPivot('name');
}
链接到的手册页中也指出了这一点:
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.
更新
尝试像这样创建 $data
数组:
$data = [];
foreach($request->input('option_id') as $id) {
$data[$id] = [ 'name' => $request->input('data')[$id] ];
}