在Laravel 5.2中,我試圖用這段代碼熱切加載用戶及其UsersSettings:App\User::with('usersettings')->get()
,但它失敗了,我可以' t似乎找出原因。這是給定的錯誤。無法在Laravel中急切加載一對一的關係
BadMethodCallException with message 'Call to undefined method Illuminate\Database\Query\Builder::usersettings()'
我讀過the laravel docs,我已經看了很多的Laracasts,這工作過,所以我得到我想的東西還真不多,可能明顯的想法。
user.php的
<?php
namespace App;
/* User with fields: id, email */
class User extends Illuminate\Database\Eloquent\Model {
protected $table = 'users';
public function usersettings() {
return $this->hasOne("App\Usersettings", "userid");
}
}
Usersettings.php
<?php
namespace App;
/* Settings with fields: id, userid, textcolor */
class Usersettings extends Illuminate\Database\Eloquent\Model {
protected $table = 'usersettings';
public function user() {
return $this->belongsTo('App\User', 'userid');
}
}
//編輯:我已經嘗試過lowercasing的秒。這個錯字可能會將它複製到SO中,但錯誤在那裏,即使在修復它之後仍然存在。
//編輯:
<?php
namespace App;
use App\UserSettings;
class User extends Illuminate\Database\Eloquent\Model {
protected $table = 'users';
public function settings() {
return $this->hasOne(UserSettings::class, "userid");
}
}
如果我運行php artisan tinker
>>>App\User::with('settings')->get()
,它工作正常,但低於
<?php
namespace App;
use App\UserSettings;
class User extends Illuminate\Database\Eloquent\Model {
protected $table = 'users';
public function usersettings() {
return $this->hasOne(UserSettings::class, "userid");
}
}
給BadMethodCallException with message 'Call to undefined method Illuminate\Database\Query\Builder::usersettings()'
當我運行php artisan tinker
>>>App\User::with('usersettings')->get()
。
public function usersettings() {
return $this->hasOne("App\Usersettings", "userid");
}
我會建議一些清理:同樣,當我的方法重命名爲abc
和運行php artisan tinker
>>>App\User::with('abc')->get()
(失敗以及)
也許在設置模型的類名中存在拼寫錯誤。嘗試'UserSettings'而不是'Usersettings'(大寫's')。你也應該試着在(')','(UserSettings)''裏面命名大寫的名字。不要以爲這是解決方案。 –
嘗試重命名'「App \ Usersettings」'到'Usersettings :: class',''App \ User''到'User :: class' – KmasterYC