我有一个模型邮件组和一个模型CommunicationType。
我邮件组可以有多个CommuniationType。这是我的关系:
邮件组模型:
public function communicationTypes()
{
return $this->hasMany('App\CommunicationType');
}CommunicationType模型:
public function mailgroup()
{
return $this->belongsTo('App\ImageRequest');
}这是我尝试存储一个新邮件组的代码。
$data = $this->request->all();
$mailgroup = new Mailgroup($data);
$mailgroup->communicationTypes()->sync($data['communication_types']);$data的结果:
array:5 [▼
"_token" => "j8lcEMggCakzANNbeVLYZttdOLUwJYKIJi0m85e6"
"name" => "a"
"administrator" => "abc"
"communication_types" => array:2 [▼
0 => "a"
1 => "a"
]
"site_id" => 4
]错误:
调用未定义的方法说明\Database\Query\Builder::sync()
我在这里做错什么了吗?
发布于 2019-04-17 09:03:30
对于一对多的关系,没有sync方法,您必须使用save或saveMany。
来自文档
雄辩为在关系中添加新模型提供了方便的方法。例如,您可能需要为Post模型插入一个新的注释。与手动设置注释上的post_id属性不同,您可以直接从关系的保存方法中插入注释:
$comment = new App\Comment(['message' => 'A new comment.']);
$post = App\Post::find(1);
$post->comments()->save($comment);如果需要保存多个相关模型,可以使用saveMany方法:
$post = App\Post::find(1);
$post->comments()->saveMany([
new App\Comment(['message' => 'A new comment.']),
new App\Comment(['message' => 'Another comment.']),
]);发布于 2019-04-17 09:01:12
邮件组还没有被拯救。先保存/创建它,然后同步:
$data = $this->request->all();
$mailgroup = Mailgroup::create($data);
$mailgroup->communicationTypes()->sync($data['communication_types']);https://stackoverflow.com/questions/55723556
复制相似问题