繁体   English   中英

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

[英]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";
}

这是我的目录映射。

在此处输入图片说明

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

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

首先,您需要在application/config/config.php启用 composer 自动加载。 只需将$config['composer_autoload']TRUE

然后你需要扩展你的composer.json来加载每个模型:

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

}

然后你需要重新生成自动加载文件(在 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());
    }
}

它对我很有用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM