【问题标题】:Use class of related model in laravel在 laravel 中使用相关模型的类
【发布时间】:2017-09-26 10:19:54
【问题描述】:

我正在尝试在 laravel eloquent 方法中使用相关模型的类名,方法是使用“USE”为模型类的名称提供别名。例如,我使用了 UserProfile 模型类:

namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use App\Models\UserProfile;

现在我在 eloquent 中使用它如下:

public function profileDetails() {
    return $this->hasOne('UserProfile', 'user_id', 'id');
}

但这会引发Class 'UserProfile' not found 的错误 如果我在这个雄辩的第一个参数中直接传递相关模型的名称和路径,那么它工作正常

public function profileDetails() {
    return $this->hasOne('App\Models\UserProfile', 'user_id', 'id');
}

我想知道为什么它不适用于 use

【问题讨论】:

  • 如果您使用的是 PHP 5.5+,您可以使用 UserProfile::class(无引号)。这不是利用您在上面声明的use 的唯一方法。 use 允许您在本地为类设置别名,但实际上不会更改类的完全限定名。
  • @JimWright 为您提供了解决方案。因为你给出了错误的类路径
  • @apokryfos 它对我有用。谢谢!!还有另一种方法可以创建此类的实例,例如。 new UserProfile
  • 基本上它是一个本地别名,每当您引用任何类静态函数或创建新实例时,您都可以将其引用为例如 new UserProfileUserProfile::find('id')

标签: php laravel-5 model eloquent relationship


【解决方案1】:

当您 use 一个类时,您只是将其导入该文件以在该文件中使用,这样您在想要引用它时就不必使用整个路径 - 将其视为别名。还值得注意的是,完整的类路径与文件中的相对类名不同。完整的类路径将始终包含完整的命名空间!

当你建立关系时,Eloquent 需要完整的类路径,以便在它自己的命名空间中操作时可以构建对象。您可以在任何类上使用::class 来获取完整的类路径,在您的情况下是App\Models\UserProfile

举以下例子:

  1. Eloquent 会认为关系类是不存在的\UserProfile

    public function profileDetails() {
        return $this->hasOne('UserProfile', 'user_id', 'id');
    }
    
  2. Eloquent 将查找确实存在的类 \App\Models\UserProfile

    public function profileDetails() {
        return $this->hasOne('App\Models\UserProfile', 'user_id', 'id');
    }
    
  3. Eloquent 将查找确实存在的类\App\Models\UserProfile!这是引用其他类最可靠的方法。

    public function profileDetails() {
        return $this->hasOne(UserProfile::class, 'user_id', 'id');
    }
    

【讨论】:

  • 谢谢!!还有另一种方法可以创建此类的实例,例如。 public function profileDetails() { return $this->hasOne(new UserProfile, 'user_id', 'id'); }
  • 不错!我不知道您可以通过实际实例。不知道有什么用例,但很容易知道;)
猜你喜欢
  • 1970-01-01
  • 2014-12-05
  • 1970-01-01
  • 2021-02-27
  • 1970-01-01
  • 2014-11-25
  • 2021-03-28
  • 2015-12-16
  • 1970-01-01
相关资源
最近更新 更多