2016-08-12 46 views
0

我正在清理我的應用程序中的代碼。似乎我對::class表示法有一種誤解。在我宣佈config/app.php提供商我可以在模型函數中使用`:: class`表示法 - Laravel

雖然可以說這個轉換:'igaster\laravelTheme\themeServiceProvider',這個 igaster\laravelTheme\themeServiceProvider::class,,我不能在車型對象確實是相同的。

舉例來說,我有

public function relateds() 
{ 
    return $this->hasMany('App\Models\Related', 'item_id')->Where('itemkind', '=', 'capacitytypes', 'and')->Where('status', '!=', '2'); 
} 

轉換後進入

public function relateds() 
{ 
    return $this->hasMany(App\Models\Related::class, 'item_id')->where('itemkind', '=', 'capacitytypes')->where('status', '!=', '2'); 
} 

我收到錯誤

FatalThrowableError in Model.php line 918: Class 'App\Models\App\Models\Action' not found

這是否意味着我不能使用模型符號,或者我做錯了?

+0

我認爲這應該工作。這個問題可能是因爲你在命名空間中引用了相關模型,使得完整的namespce以一種你不想要的方式出現。你有沒有注意到'App \ Models \ App \ Models \ Action'的路徑問題?改爲使用'Related :: class'。 – Qevo

+0

Try \ App \ Models \相關::類代替(在開始時額外的反斜槓) –

+0

曼努埃爾,它的工作。令我驚訝的是,我自己試圖做到這一點。我必須從應用程序積極反饋。謝謝。請將您的評論升級爲答案。 – Peter

回答

2

命名空間的行爲與此上下文中的文件路徑有些類似,因爲當您在整個代碼中引用一個命名空間時,可以相對(相對於當前命名空間)或絕對(全名空間)引用它們。

當你在一個名字空間像這樣的文件中時,如果你省略了前導\字符,那麼你就是相對引用了。這就是爲什麼它尋找App\Models\App\Models\Action

文件config/app.php沒有名稱空間,因此您提供的任何名稱空間都假定爲相對於根名稱空間,所以您不需要前導\字符。

僅供參考,您可以採取一些措施來解決您的問題。

  • 首先,在意見提出,你可以在一開始把\所以它變成了:

    public function relateds() 
    { 
        return $this->hasMany(\App\Models\Related::class, 'item_id')->where('itemkind', '=', 'capacitytypes')->where('status', '!=', '2'); 
    } 
    
  • 其次,你可以在你的文件的頂部use類,剛過命名空間聲明,然後在定義關係時忽略完整名稱空間,如下所示:

    <?php 
    
    namespace App\Models; 
    
    use App\Models\Related; 
    
    class Action extends Model 
    { 
        // ... 
    
        public function relateds() 
        { 
         return $this->hasMany(Related::class, 'item_id')->where('itemkind', '=', 'capacitytypes')->where('status', '!=', '2'); 
        } 
    
  • 最後一個更簡單地說,因爲您的RelatedAction模型都位於相同的App\Models命名空間中,所以在定義關係時可以完全省略命名空間,而不必將其置於頂部use。所以,你最終會得到這樣的:

    public function relateds() 
    { 
        return $this->hasMany(Related::class, 'item_id')->where('itemkind', '=', 'capacitytypes')->where('status', '!=', '2'); 
    } 
    
相關問題