laravel - 如何访问模型中访问器方法中的关系 拉拉维尔 8?
问题描述
我有这个Course
与 . 相关的模型academicPath
,现在我正在创建这个访问器long_name
,但无法访问academicPath
.
class Course extends Model
{
/// ...
protected $appends = [
'long_name'
];
public function academicPath()
{
return $this->belongsTo(\App\Models\AcademicPath::class);
// return $this->hasOne(\App\Models\AcademicPath::class);
}
public function getLongNameAttribute()
{
return $this->academic_path->academic_path_name . " [" . $this->course_year . "]" ;
}
}
错误 :
{message: "Attempt to read property "academic_path_name" on null", exception: "ErrorException",…}
exception: "ErrorException"
file: "/var/www/html/app/Models/Course.php"
line: 57
message: "Attempt to read property "academic_path_name" on null"
trace: [{file: "/var/www/html/app/Models/Course.php", line: 57, function: "handleError",…}, {,…}, {,…}, {,…},…]
解决方案
解决了,通过替换
$this->academic_path
和
$this->academicPath
并确保该值不为空,因为它不是必需的。
public function getLongNameAttribute()
{
if (is_null($this->academicPath)) {
return "... [" . $this->course_year . "]";
} else {
return $this->academicPath->academic_path_name
. " [" . $this->course_year . "]";
}
}
推荐阅读
- python - 了解 fftfreq 函数的输出和图像中单行的 fft 图
- google-play - 一个意料之外的问题发生了。请稍后再试。(686578003)
- google-authentication - 谷歌登录集成 UI 模拟器问题 iOS 13 Xode 11
- javascript - Fullcalendar.io 将一些事件显示为一条细垂直线
- ssh - 来自本地机器的远程 SSH:连接被拒绝
- javascript - 如何计算与 javascript 一起使用的视频的带宽量?
- python - 在 Celery 链中并行运行结果列表
- flutter - 颤振 - 剪辑路径
- java - Dockerfile 中的打包步骤是下载依赖项,尽管前面有一个步骤来解决依赖项
- php - 将 JSON 对象从 ajax 传递到 PHP 脚本