laravel多对多关系不存储在透视表中



我有两个表开发人员表和技能表,它们与多对多关系developer_skill表相关联。我想在数据透视表中存储developer_id和skill_id。

但是当开发人员添加他们的技能并提交时返回错误。

在开发表中添加数据,但在透视表中未添加数据。误差

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'developer_id' cannot be null (SQL: insert into `developer_skill` (`developer_id`, `skill_id`) values (, 5))

开发控制器存储数据

namespace AppHttpControllers;
use IlluminateHttpRequest;
use AppDeveloper; 
use AppSkill as skill;
class developerController extends Controller
{
public function __construct(Developer $Developer, skill $skill)
{
$this->Developer = $Developer;
$this->skill = $skill;
}
public function store(Request $request)
{
$skills = implode(',', $request->user_skills);

$data = array(
'name' => $request->name,
'skills' => $skills,
);

if ($this->Developer->create($data)) {
$syncTagData = array();
if (!empty($request->user_skills)) {
$syncTagData = $request->user_skills;
}

$this->Developer->user_skills()->sync($syncTagData);
}
}
}

developer_skill

developer_id
skill_id
<<p>技能模型/strong>
public function users()
{
return $this->belongsToMany(Developer::class);
}
<<p>开发模型/strong>
public function user_skills()
{
return $this->belongsToMany('AppSkill');
}

你的问题在这里:

if ($this->Developer->create($data)) {
$syncTagData = array();
if (!empty($request->user_skills)) {
$syncTagData = $request->user_skills;
}
$this->Developer->user_skills()->sync($syncTagData);
}

$this->Developer已经是Developer的一个实例,所以当你调用create()时,它构建的查询不是你可能期望的。

你有两个选择:

使用模型Facade(我的首选):

if ($developer = Developer::create($data)) {
$syncTagData = array();
if (!empty($request->user_skills)) {
$syncTagData = $request->user_skills;
}
$developer->user_skills()->sync($syncTagData);
}

使用上面的方法,你应该能够删除你的构造函数,因为它不需要。

或者在$this->developer上设置属性并保存:

$this->Developer->name = $data['name'];
$this->Developer->skills = $data['skills'];
if ($this->Developer->save()) {
$syncTagData = array();
if (!empty($request->user_skills)) {
$syncTagData = $request->user_skills;
}
$developer->user_skills()->sync($syncTagData);
}

还要注意user_skills关系名称。约定是camelCase,所以你可能会受益于将其更改为userSkills,否则你可能会发现当Laravel在幕后执行其魔法时发生了奇怪的事情。

最新更新