我有两个模型:User
和 Form
。 Form
模型有两个 belongsTo
关系:
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
是一个可为 null 的整数列。
使用 artisan tinker,我尝试将用户分配为表单的管理员(使用 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');
}
}
用户
模型:
<?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);
}
}
最佳答案
Laravel 的相对命名空间类引用 App\User
和 App\Form
可能存在命名空间解析问题。
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.
- 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.
尝试在 User
和 Form
类引用之前删除 App\
命名空间声明,或者在它们前面加上另一个 \
使它们完全合格。
关于php - Laravel Eloquent 关系 - 奇怪的路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40915396/