php - Laravel Eloquent 关系 - 奇怪的路径

标签 php laravel eloquent

我有两个模型:UserFormForm 模型有两个 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\UserApp\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.

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\ 命名空间声明,或者在它们前面加上另一个 \ 使它们完全合格。

关于php - Laravel Eloquent 关系 - 奇怪的路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40915396/

相关文章:

php - SELECT * 会比 40 列列表更快吗?

javascript - 将 csv 文件从 php 发送到浏览器

php - 使用 PDO 插入值 '000' 结果为 NULL

javascript - Laravel 中的路由,ajax 中的 URL 解析

mysql - 用laravel上传图片并进行图片干预到本地路径

php - Laravel Eloquent : How to select friend user model?

请求数据库后 PHP 7.2 password_verify() 不工作

javascript - Vue 计算属性返回一个 promise ?

php - laravel 验证使用 "numeric"规则失败,数据来自表单中的数字

php - 如何在 helper 类中使用 laravel Eloquent 模型