首页 > 解决方案 > 如何访问模型中访问器方法中的关系 拉拉维尔 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",…}, {,…}, {,…}, {,…},…]

标签: laravellaravel-8

解决方案


解决了,通过替换

$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 . "]";
        }
    }

推荐阅读