2016-12-01 20 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'); 
} 
} 

然后一切工作正常(重新启动工匠鼓捣之后)。