Laravel 5.0 sync()关于存储时关系不起作用

问题描述 投票:0回答:2

我有一个模型Mailgroup和一个模型通信类型。

I Mailgroup可以有多个CommunicationTypes。这是我的关系:

邮件组模型:

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
]

错误:

调用未定义的方法Illuminate \ Database \ Query \ Builder :: sync()

我在这里做错了吗?

php laravel laravel-5 eloquent
2个回答
3
投票

对于一对多关系没有sync方法,你将不得不使用savesaveMany

来自docs

Eloquent提供了为关系添加新模型的便捷方法。例如,您可能需要为Post模型插入新的Comment。您可以直接从关系的save方法插入Comment,而不是在Comment上手动设置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.']),
]);

0
投票

Mailgroup尚未保存。首先保存/创建它,然后同步:

$data = $this->request->all();
$mailgroup = Mailgroup::create($data);
$mailgroup->communicationTypes()->sync($data['communication_types']);
© www.soinside.com 2019 - 2024. All rights reserved.