CodeIgniter Eloquent 模型关系 Class 未找到模型

CodeIgniter Eloquent Model Relationship Class Model Not Found

我正在尝试将 eloquent 实施到我的 CodeIgniter 项目中。

当我在我的项目中调用模型时效果很好(它从我的数据库中提供数据)。但是当我试图为其模型调用关系时,它出错了并显示此消息:

An uncaught Exception was encountered
Type: Error

Message: Class 'application\models\Profile' not found

Filename: /var/www/public/chupspace-git/vendor/illuminate/database/Eloquent/Model.php

Line Number: 750

Backtrace:

File: /var/www/public/chupspace-git/application/models/User.php
Line: 12
Function: hasOne

File: /var/www/public/chupspace-git/vendor/illuminate/database/Eloquent/Model.php
Line: 2638
Function: profile

File: /var/www/public/chupspace-git/vendor/illuminate/database/Eloquent/Model.php
Line: 2573
Function: getRelationshipFromMethod

File: /var/www/public/chupspace-git/vendor/illuminate/database/Eloquent/Model.php
Line: 3263
Function: getAttribute

File: /var/www/public/chupspace-git/application/controllers/UserController.php
Line: 53
Function: __get

File: /var/www/public/chupspace-git/index.php
Line: 357
Function: require_once

我在 composer.json

中使用 "illuminate/database": "5.0.28",

这是我的模型

User.php

if (!defined('BASEPATH')) exit('No direct script access allowed');

use \Illuminate\Database\Eloquent\Model as Eloquent;

class User extends Eloquent {
    protected $table = "users";

    public function profile()
    {
        return $this->hasOne('application\models\Profile');
    }
}

Profile.php

if (!defined('BASEPATH')) exit('No direct script access allowed');

use \Illuminate\Database\Eloquent\Model as Eloquent;

class Profile extends Eloquent {
    protected $table = "user_profiles";
}

这是我的目录映射。

让我知道是否缺少信息,以便我更新此线程。 你的帮助对我来说非常宝贵。谢谢。

您需要在使用之前加载所有关系 class。

首先,您需要在 application/config/config.php 中启用作曲家自动加载。只需将 $config['composer_autoload'] 设置为 TRUE

然后您需要扩展 composer.json 以加载每个模型:

{
"autoload": {
    "classmap": ["application/models/"]
}

}

然后你需要重新生成自动加载文件(运行 in cli):

composer dump-autoload

应该可以。还有很多其他的方法,但我认为这是最清楚的。

我找到了解决办法。我们只需要改变

$this->hasOne('application\models\Profile');

成为

$this->hasOne(new Profile());

这是我的完整代码。

<?php

if (!defined('BASEPATH')) exit('No direct script access allowed');

use \Illuminate\Database\Eloquent\Model as Eloquent;

class User extends Eloquent {
    protected $table = "users";

    public function profile()
    {
        // dd();
        return $this->hasOne(new Profile());
    }
}

对我来说效果很好。