Man*_*anu 0 php model relationship eloquent laravel-5
我试图通过使用"使用"给了别名,模型类的名称使用在laravel雄辩的方法相关模型的类名.例如,我使用过UserProfile模型类:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use App\Models\UserProfile;
Run Code Online (Sandbox Code Playgroud)
而现在我正在以雄辩的方式使用它,如下所示:
public function profileDetails() {
return $this->hasOne('UserProfile', 'user_id', 'id');
}
Run Code Online (Sandbox Code Playgroud)
但这会引发一个错误.Class 'UserProfile' not found
如果我直接在这个雄辩的第一个参数中传递相关模型的名称和路径,那么它的工作正常
public function profileDetails() {
return $this->hasOne('App\Models\UserProfile', 'user_id', 'id');
}
Run Code Online (Sandbox Code Playgroud)
我想知道为什么它没有合作 use
当你use是一个类时,你只是导入它以便在该文件中使用,这样当你想引用它时就不必使用整个路径 - 把它想象成一个别名.还值得注意的是,完整的类路径与文件中的相对类名称不同.完整的类路径将始终包含完整的命名空间!
在设置关系时,Eloquent需要完整的类路径,以便在使用自己的命名空间时可以构建对象.您可以::class在任何类上使用以获取完整的类路径,在您的情况下App\Models\UserProfile.
请看以下示例:
Eloquent会认为关系类\UserProfile不存在.
public function profileDetails() {
return $this->hasOne('UserProfile', 'user_id', 'id');
}
Run Code Online (Sandbox Code Playgroud)Eloquent会寻找\App\Models\UserProfile确实存在的类!
public function profileDetails() {
return $this->hasOne('App\Models\UserProfile', 'user_id', 'id');
}
Run Code Online (Sandbox Code Playgroud)Eloquent会寻找\App\Models\UserProfile确实存在的类!这是引用其他类的最可靠方法.
public function profileDetails() {
return $this->hasOne(UserProfile::class, 'user_id', 'id');
}
Run Code Online (Sandbox Code Playgroud)| 归档时间: |
|
| 查看次数: |
646 次 |
| 最近记录: |