【发布时间】:2015-11-24 10:47:10
【问题描述】:
下面的代码显示了我的 Eloquent Link 类中的一个方法。创建一个新的Link 后,我想创建一个相关的对象LinkContact,然后用新的Link 创建一个associate()。
创建LinkContact 时,我在访问Link 的id 属性时遇到问题。只有在为新的相关对象 (LinkContact) 执行 create 方法时,Link id 值才会显示为不可访问。
在调用 create 方法之前使用 Laravel Debugbar 一行我已经记录了 Link id,我可以看到它很好!任何想法为什么会发生这种情况以及为什么我无法访问该值?!和范围有关吗?
请注意cmets在哪里
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
}
【问题讨论】: