【问题标题】:laravel MyModelClass not found in 1:1 relationshiplaravel MyModelClass 在 1:1 关系中找不到
【发布时间】:2015-01-19 17:21:19
【问题描述】:

我的应用程序中有一个 User 和一个 Profile 类,它们之间的关系是 1:1。 在我的ProfileController@show 中,我可以为它们中的每一个完美地实例化和构建查询,但这两行:

$userProfile=$profile->with('user')->where('id',1)->firstOrFail();
$userProfile=$user->with('profile')->where('id',3)->firstOrFail();

第一个发送一个致命错误异常,消息为:“Class User Not Found”,第二个消息是“Class Profile Not Found”

我也尝试过外观和构建查询的不同方式,但没有奏效。

根据这个question我认为我的关系有问题。我明确地传递了foreign_key,但它不起作用。

这里有一些细节:

用户类别:

class User extends \Eloquent implements UserInterface, RemindableInterface
{

    public function profile()
    {
        return $this->hasOne('Profile', 'id');
    }

}

个人资料类

class Profile extends \Eloquent
{

    public function user()
    {
        return $this->belongsTo('User', 'id');
    }
}

数据库架构: 表“用户”

id
password
email
username

表格“个人资料”

id
user_id
about

提前致谢。

【问题讨论】:

  • 类是在模型的子文件夹中还是在包中?为什么 \Eloquent 有一个前导反斜杠?你做了php artisan dump-autoload
  • 它们在我的命名空间中,如下所示:Artronics\UserArtronics\Profile 带有 psr-4 自动加载。是的,我实际上尝试了很多次composer dump-autoload
  • 我刚试过php artisan dump-autoload,但结果还是一样。顺便说一句,composer dump-autoloadphp artisan dump-autoload 有什么区别?

标签: php laravel


【解决方案1】:

这个怎么样?

class User extends \Eloquent implements UserInterface, RemindableInterface
{

    public function profile()
    {
        return $this->hasOne('Profile', 'user_id');
    }

}

不应该是外键吗? http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Relations/HasOne.html

【讨论】:

  • 感谢@xjaphx ,由于我遵循所有 laravel 约定,实际上不需要明确外键。顺便说一句,我尝试了iduser_id,两者都有效! (插入完整的类路径后)
  • @SeyedJalalHosseini 虽然接受的答案为您解决了命名空间,但这个答案是定义关系的正确方法。您的设置“有效”,但绝对不是您所期望的。
  • 是的@xjaphx 我再次检查了文档。你完全正确。谢谢
【解决方案2】:

如果您的模型有命名空间,您需要插入完整的命名空间类作为参数。否则 Eloquent 不知道在哪里可以找到该类。

或者您需要将模型添加到 app/config/app.php 中的类映射

class User extends \Eloquent implements UserInterface, RemindableInterface
{
    public function profile()
    {
        return $this->hasOne('\Path\TO\Model\Profile', 'id');
    }
}

【讨论】:

    猜你喜欢
    • 2014-04-19
    • 1970-01-01
    • 2019-05-10
    • 1970-01-01
    • 2022-09-23
    • 1970-01-01
    • 2015-05-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多