2016-12-01 43 views
3

我有兩個型號:UserForm。該Form模型有兩個belongsTo關係:Laravel雄辯的關係 - 奇怪的路徑

class Form extends Model 
{ 

    public function user() 
    { 
     return $this->belongsTo(User::class); 
    } 

    public function manager_user() 
    { 
     return $this->belongsTo(User::class, 'manager_id'); 
    } 
} 

manager_id是空整型列。

使用Artisan鼓搗,我嘗試將用戶作爲經理分配到形式(使用these methods):

$manager = App\User::findOrFail(1); 
$form = App\Form::findOrFail(1); 
$form->manager_user()->assign($manager); 

,但我得到的錯誤:

$form->manager_user()->associate($gacek) 
PHP Fatal error: Class 'App\App\User' not found in /var/www/html/test/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php on line 779              

[Symfony\Component\Debug\Exception\FatalErrorException] 
Class 'App\App\User' not found 

我在做什麼錯?爲什麼框架試圖搜索App\App\User而不是App\User

這是Laravel 5.3的全新安裝。

編輯 完整模型命名空間的文件:

Form型號:

<?php 

namespace App; 

use Illuminate\Database\Eloquent\Model; 

class Form extends Model 
{ 
public function user(){ 
    return $this->belongsTo("App\User"); 
} 

public function manager_user(){ 
    return $this->belongsTo("App\User", 'manager_id'); 
} 
} 

User型號:

<?php 

namespace App; 

use Illuminate\Notifications\Notifiable; 
use Illuminate\Foundation\Auth\User as Authenticatable; 

class User extends Authenticatable 
{ 
use Notifiable; 

protected $fillable = [ 
    'name', 'email', 'password', 'surname', 'login', 'sign' 
]; 

protected $hidden = [ 
    'password', 'remember_token', 
]; 

public function forms(){ 
    return $this->hasMany(Form::class); 
} 
} 
+1

也許命名空間問題。 –

+2

你可以顯示你的模型的命名空間! –

+0

當然,請參閱我的編輯。 – Gacek

回答

3

你可能有一個名稱空間解析的問題與相關的命名空間類參考文獻App\User a nd App\Form與Laravel。

By default, this directory is namespaced under App and is autoloaded by Composer using the PSR-4 autoloading standard. You may change this namespace using the app:name Artisan command.

From Laravel Docs

  1. Relative names always resolve to the name with namespace replaced by the current namespace. If the name occurs in the global namespace, the namespace\ prefix is stripped. For example namespace\A inside namespace X\Y resolves to X\Y\A. The same name inside the global namespace resolves to A.

Namespace Resolution rules

嘗試之前你UserForm類引用去除App\命名空間聲明或與其他\前綴,使它們完全合格。

+0

是的,情況就是如此。另請參閱我的答案。 – Gacek

0

由於@Kevin Stitch暗示我有相對命名空間的問題。

在我Form模型我調整的關係有絕對路徑:

class Form extends Model 
{ 
public function user(){ 
    return $this->belongsTo("\App\User"); 
} 

public function manager_user(){ 
    return $this->belongsTo("\App\User", 'manager_id'); 
} 
} 

然後一切工作正常(重新啓動工匠鼓搗之後)。