下面的代码显示了我的Eloquent Link
类中的一个方法。在创建一个新的Link
之后,我想创建一个相关的对象LinkContact
,然后用新的Link
来创建associate()
。
创建LinkContact
时,我在访问Link
的id属性时遇到问题。只有在为新的相关对象(LinkContact
)执行创建方法时,Link
id值才显得不可访问。
在调用create方法之前的一行使用Laravel Debugbar,我已经记录了Link
id,我可以很好地看到它!有什么想法吗?为什么会发生这种情况,为什么我无法获得价值?!这与范围有关吗?
请注意的注释位置
public function createActiveLink($students)
{
$links = [];
foreach ($students as $student) {
$newLink = $this->create([
'token' => $student->saudi_nid,
'status' => 'active',
'course_title' => $student->course_title,
'university_id' => $student->university_id,
'student_id' => $student->id,
'institution_id' => $student->institution_id,
'course_id' => $student->course_id,
]);
$studentContacts = $student->institutionContacts;
if ($studentContacts) {
foreach ($studentContacts as $studentContact) {
/* I get the value here, no problems */
'Debugbar::info($newLink->id);
$linkContact = $this->contacts()->create([
'type' => $studentContact->pivot->type,
'institution_contact_id' => $studentContact->pivot->institution_contact_id,
/* $newLink->id returns nothing here */
'link_id' => $newLink->id, here!!
]);
$newLink->contacts()->associate($linkContact);
$newLink->save();
}
}
$links[] = $newLink;
}
return $links;
}
我在尝试上述代码时收到的错误:
SQLSTATE[23000]: Integrity constraint violation: 1048
Column 'link_id' cannot be null
(SQL: insert into `link_contacts`
(`type`, `institution_contact_id`, `link_id`, `updated_at`, `created_at`)
values (1, 1, , 2015-11-24 10:26:32, 2015-11-24 10:26:32))
C:'...'vendor'laravel'framework'src'Illuminate'Database'Connection.php#631
SQLSTATE[23000]: Integrity constraint violation: 1048
Column 'link_id' cannot be null
C:'...'vendor'laravel'framework'src'Illuminate'Database'Connection.php#380
重申一下,我确实在Laravel Debugbar中得到了值,但在它之后的方法调用中没有!
编辑:
在我的LinkContact
类中,link_id
在我的可填充属性中:
class LinkContact extends Model
{
protected $fillable = ['type', 'link_id', 'institution_contact_id'];
// rest of the class
}
值得注意的是:
$newLink->contacts()->associate($linkContact);
在这种情况下,运行一个查询,如:
UPDATE `link_contacts` SET `link_id` = 1 WHERE `id` = 4;
因此,如果您在create中设置link_id
,则不需要运行associate。如果内存可用,则可以运行$newLink->contacts()->create([...])
,而不是同时运行create()
和associate()
。
由于Eloquent的工作方式,外键将始终通过运行任何旨在自动插入此数据的辅助方法来更新/插入,但您需要手动指定密钥,这意味着它受$fillable
的约束,所以我会对此进行研究,如果您当前没有,请将link_id
添加到该数组中。
尝试
$newLink->save();
在调用之前
$newLink->id
id是在数据保存到数据库中之后才生成的,因此在此之前无法知道它。