laravel 多对多关系未存储在数据透视表中 table

laravel many to many relationship not store in pivot table

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

但是当开发者添加他们的技能并提交时 return 错误。

在开发者 table 中添加了数据,但在 pivot table 中未添加数据。 错误

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

开发者控制器存储数据

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Developer; 
use App\Skill 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

技能模型

public function users()
{
    return $this->belongsToMany(Developer::class);
}

开发者模式

public function user_skills()
    {
        return $this->belongsToMany('App\Skill');

}

你的问题在这里:

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 关系名称。惯例是驼峰式命名,因此您可能会从将其更改为 userSkills 中受益,否则当 Laravel 在幕后发挥其魔力时,您可能会发现奇怪的事情发生。