2017-02-22 61 views
0

由於型號名稱的更改,我的類Student現在不能正常工作。 與數據庫名爲assosLaravel 5 belongsTo(classname :: class)不起作用

`id` int(10) unsigned NOT NULL AUTO_INCREMENT, 
`name` text COLLATE utf8mb4_unicode_ci NOT NULL, 
`student_id` text COLLATE utf8mb4_unicode_ci NOT NULL, 
`created_at` timestamp NULL DEFAULT NULL, 
`updated_at` timestamp NULL DEFAULT NULL, 

與模型Asso鏈接,

查詢App\Asso::first()->belongsTo(Student::class)返回null

App\Asso::first()->belongsTo('App\Student','student_id')返回相關的學生查詢。

我不明白爲什麼belongsTo(Student::class)無法正常工作。你能幫我弄清楚嗎?

非常感謝

回答

1

Eloquent: Relationships One To One

口才通過檢查的關係,方法的名稱 和後面添加_id方法名確定默認外鍵名。

既然你似乎是定義關係內聯,方法名可能不是student所以它不是尋找student_id,它在尋找mehtodname_id

在你的第二個例子中,你告訴它在哪個字段中查找關係,所以它看着正確的一個。

與問題無關,但您真的濫用關係方法。這些應該在模型中定義。

+0

不要擔心關係的使用。這只是爲了說明這篇文章:)非常感謝! –