2016-08-18 139 views
0

在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()(失敗以及)

+0

也許在設置模型的類名中存在拼寫錯誤。嘗試'UserSettings'而不是'Usersettings'(大寫's')。你也應該試着在(')','(UserSettings)''裏面命名大寫的名字。不要以爲這是解決方案。 –

+0

嘗試重命名'「App \ Usersettings」'到'Usersettings :: class',''App \ User''到'User :: class' – KmasterYC

回答

0

您定義的關係時,在用戶模式輸入有誤 將用戶名和用戶設置命名爲 將字段'userid'重命名爲'user_id', 將'Usersettings'模型重命名爲'UserSettings'。

這樣你就不需要明確定義表名和外鍵,因爲你按照約定和Laravel可以「猜測」那些。

您還可以將關係'usersettings()'重命名爲'settings()',因爲它顯然是用戶的設置。然後你可以像這樣獲取它:'User :: with('settings') - > get()'。

+0

我完全陷入困境。我嘗試了三種方法名稱來替代'usersettings()'方法:用戶設置,關係和設置。 'App \ User :: with('usersettings') - > get()'拋出一個異常,'App \ User :: with('myrelation') - > get()'也會拋出異常,但App \ User ::與('設置') - > get()'工作。那可能怎麼樣? – stealthjong

+0

你必須忘記一些東西,將你當前的代碼放在小提琴或主題上並提供一個鏈接。 – PawelMysior

+0

另見... – stealthjong