【发布时间】:2021-05-31 16:29:38
【问题描述】:
我有两个表开发人员表和技能表,它们与多对多关系 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 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_id
skill_id
技能模型
public function users()
{
return $this->belongsToMany(Developer::class);
}
开发者模型
public function user_skills()
{
return $this->belongsToMany('App\Skill');
}
【问题讨论】:
-
你在哪里设置
$this->developer在你的控制器中?你能在你的控制器中显示整个方法,包括声明和任何构造函数吗? -
好的,我正在更新问题
-
我已经更新了我的控制器
-
查看您的路线也可能会有所帮助。从本质上讲,
$this->developer看起来像是一个新的Developer,而不是从数据库中解析出来的。这就是 ID 为空的原因。 -
对不起,我刚刚意识到我的答案离题了。我完全误读了你的代码!我再看看
标签: laravel eloquent pivot relationship eloquent-relationship