Php 在laravel中使用相关模型类
我试图在laravel eloquent方法中使用相关模型的类名,方法是使用“use”为模型类的名称提供别名。例如,我使用了UserProfile模型类:Php 在laravel中使用相关模型类,php,laravel-5,model,eloquent,relationship,Php,Laravel 5,Model,Eloquent,Relationship,我试图在laravel eloquent方法中使用相关模型的类名,方法是使用“use”为模型类的名称提供别名。例如,我使用了UserProfile模型类: namespace App\Models; use Illuminate\Database\Eloquent\Model; use App\Models\UserProfile; 现在我用它来雄辩如下: public function profileDetails() { return $this->hasOne('UserP
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use App\Models\UserProfile;
现在我用它来雄辩如下:
public function profileDetails() {
return $this->hasOne('UserProfile', 'user_id', 'id');
}
但这会引发一个错误,即未找到类“UserProfile”
若我在这个雄辩的例子的第一个参数中直接传递了相关模型的名称和路径,那个么它就可以正常工作了
public function profileDetails() {
return $this->hasOne('App\Models\UserProfile', 'user_id', 'id');
}
我想知道,当您使用一个类时,为什么它不使用
use
,而您只是导入该类以在该文件中使用,这样当您想要引用它时就不必使用整个路径-将其视为一个别名。还值得注意的是,完整类路径与文件中的相对类名不同。完整的类路径将始终包含完整的命名空间
当您设置关系时,Elount需要完整的类路径,以便在自己的命名空间中操作时可以构建对象。您可以在任何类上使用::class
,以获取完整的类路径,在您的示例中是App\Models\UserProfile
举以下例子:
\UserProfile
public function profileDetails() {
return $this->hasOne('UserProfile', 'user_id', 'id');
}
\App\Models\UserProfile
public function profileDetails() {
return $this->hasOne('App\Models\UserProfile', 'user_id', 'id');
}
\App\Models\UserProfile
!这是引用其他类最可靠的方法
public function profileDetails() {
return $this->hasOne(UserProfile::class, 'user_id', 'id');
}
当您
使用
一个类时,您只需导入该类以在该文件中使用,这样您就不必在引用该类时使用整个路径—请将其视为别名。还值得注意的是,完整类路径与文件中的相对类名不同。完整的类路径将始终包含完整的命名空间
当您设置关系时,Elount需要完整的类路径,以便在自己的命名空间中操作时可以构建对象。您可以在任何类上使用::class
,以获取完整的类路径,在您的示例中是App\Models\UserProfile
举以下例子:
\UserProfile
public function profileDetails() {
return $this->hasOne('UserProfile', 'user_id', 'id');
}
\App\Models\UserProfile
public function profileDetails() {
return $this->hasOne('App\Models\UserProfile', 'user_id', 'id');
}
\App\Models\UserProfile
!这是引用其他类最可靠的方法
public function profileDetails() {
return $this->hasOne(UserProfile::class, 'user_id', 'id');
}
如果您使用的是PHP5.5+,那么可以使用
UserProfile::class
(无引号)。这不是利用上面声明的use
的唯一方法<代码>使用允许您在本地为类别名,但实际上不会更改类的完全限定名。@JimWright已为您提供了解决方案。因为你上错了课path@apokryfos它对我有用。谢谢还有一种方法我们可以创建这个类的实例,例如,newuserprofile
基本上它是一个本地别名,当你引用任何一个类的静态函数或创建一个新实例时,你可以引用它,例如newuserprofile
或UserProfile::find('id'))
如果您使用的是PHP5.5+,则可以使用UserProfile::class
(无引号)。这不是利用上面声明的use
的唯一方法<代码>使用允许您在本地为类别名,但实际上不会更改类的完全限定名。@JimWright已为您提供了解决方案。因为你上错了课path@apokryfos它对我有用。谢谢还有一种方法我们可以创建这个类的实例,例如,newuserprofile
基本上它是一个本地别名,每当你引用任何类的静态函数或创建一个新实例时,你都可以引用它,例如newuserprofile
或UserProfile::find('id')
谢谢!!还有一种方法可以创建这个类的实例,例如,public function profileDetails(){return$this->hasOne(newuserprofile,'user_id','id');}
Nice!我不知道你能通过一个实际的例子。不确定有什么用例,但很容易知道;)谢谢还有一种方法可以创建这个类的实例,例如,public function profileDetails(){return$this->hasOne(newuserprofile,'user_id','id');}
Nice!我不知道你能通过一个实际的例子。不确定有什么用例,但很容易知道;)