【发布时间】:2018-07-19 05:57:48
【问题描述】:
所以当涉及到一个项目的多对多关系时,我开始与 Doctrine2 斗争,其中关系有 1 个额外的列。
我有以下表格:
- 个人资料
- 身份证
- 额外数据
-
技能
- 身份证
- 姓名
-
profile_has_skills
- profile_id
- skill_id
- 级别
现在我稍后添加了级别列,并注意到发生了一些问题,当然,当我尝试创建关系时,我现在缺少级别。 我的问题是,使用下面的代码,我将如何在我的学说中添加它?
我的控制器:
public function store(Request $request)
{
$time = new DateTime();
$this->validate($request, [
'name' => 'required',
'lastname' => 'required',
'gender' => 'required',
'profile_skills' => 'required'
]);
$this->em->getConnection()->beginTransaction();
try {
$profile = new Profile(
$request->input('company_id'),
$request->input('name'),
$request->input('lastname'),
$request->input('gender'),
new DateTime(),
$time,
$time
);
$company = $this->em->getRepository(Company::class)->find($request->input('company_id'));
$profile->addCompany($company);
foreach($request->input('profile_skills') as $skill => $level) {
$skill = $this->em->getRepository(Skill::class)->find($skill);
$skill->level = $level;
$profile->addSkill($skill);
}
$this->em->persist($profile);
$this->em->flush();
$this->em->getConnection()->commit();
} catch (OptimisticLockException $e) {
$this->em->getConnection()->rollBack();
throw $e;
}
return redirect(route('profiles.index'));
}
我的 ProfileHasSkill 实体如下所示:
/**
* @ORM\Entity
* @ORM\Table(name="profile_has_skill")
*
*/
class ProfileHasSkill
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
protected $id;
/**
* @Column(type="integer", name="profile_id")
*/
protected $profile_id;
/**
* @Column(type="integer", name="skill_id")
*/
protected $skill_id;
/**
* @Column(type="integer", name="level")
*/
protected $level;
/**
* @param $profile_id
* @param $skill_id
* @param $level
*/
public function __construct($profile_id, $skill_id, $level = 0)
{
$this->profile_id = $profile_id;
$this->skill_id = $skill_id;
$this->level = $level;
}
我在个人资料实体中的 addSkill 方法如下:
public function addSkill(Skill $skill)
{
if ($this->skills->contains($skill)) {
return;
}
return $this->skills->add($skill);
}
但每当我尝试运行它时,都会出现以下错误
An exception occurred while executing
'INSERT INTO profile_has_skill (profile_id, skill_id) VALUES (?, ?)'
with params [3, 2]: SQLSTATE[HY000]: General error: 1364 Field 'level'
doesn't have a default value
现在我知道摆脱这个错误的一种方法是在数据库中设置一个默认值,但我更愿意找出为什么它没有提高我也通过的技能水平?
【问题讨论】:
标签: php laravel doctrine-orm many-to-many entity-relationship