如何访问模型中访问器方法中的关系|拉维尔8?

时间:2021-02-18 10:28:29

标签: laravel laravel-8

我有这个与 Course 相关的 academicPath 模型,现在我正在创建这个名为 long_name 的访问器,但无法访问 academicPath 下的 Academic_path_name。

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",…}, {,…}, {,…}, {,…},…]

1 个答案:

答案 0 :(得分:0)

解决,通过替换

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