【问题标题】:many-to-many relationship - save data多对多关系 - 保存数据
【发布时间】:2018-07-11 11:51:21
【问题描述】:

我在Film 和Performer 模型之间建立了关系。

电影模特:

public function Performers()
{
    return $this->belongsToMany('App\Performer');
}

表演者模型:

public function Films()
{
  return $this->belongsToMany('App\Films');
}

如果我要手动添加数据,我已经创建了表 film_performer 并且关系有效。

我在发送表单后将数据保存到film_performer 时遇到问题。

我将它附加到控制器中。

$film->performers()->attach($request->performers);

我没有任何错误。我使用dd($request) 来检查数组执行者,一切正常

【问题讨论】:

标签: php laravel


【解决方案1】:

将$request->performers 更改为$request->performers->pluck('id'):

$film->performers()->attach($request->performers)

attach 方法需要一个 id 数组。

https://laravel.com/docs/5.5/eloquent-relationships#updating-many-to-many-relationships

为方便起见,附加和分离也接受 ID 数组作为输入:

$user = App\User::find(1);

$user->roles()->detach([1, 2, 3]);

$user->roles()->attach([ 1 => ['expires' => $expires], 2 => ['过期' => $过期] ]);

【讨论】:

  • 它不起作用。我以前用标签做这个,它可以工作 $film->tags()->attach($request->tags);
猜你喜欢
  • 2014-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-31
  • 1970-01-01
  • 1970-01-01
  • 2015-07-02
相关资源
最近更新 更多