【发布时间】:2019-10-25 19:15:44
【问题描述】:
我正在编写一个管理培训课程的 Laravel 应用程序。
每门课程都由一个课程模型表示。
一门课程可以有多个日期 - 这些由 CourseDate 模型表示,两者之间具有 hasMany 关系:
每门课程还有一个“日期模板”,即 CourseDate,但带有一个“is_template”布尔集。
我想在 Course 模型上创建一个访问器来检索其日期模板。
每个模型的(相关)代码是:
class Course extends Model {
public function getDateTemplateAttribute() {
$dates = $this->dates;
$filtered = $dates->where('is_template', true);
$template = $filtered->first();
return $template;
}
public function dates() {
$result = $this->hasMany( CourseDate::class );
return $result;
}
}
class CourseDate extends Model {
public function course() {
return $this->belongsTo( Course::class );
}
}
然后,在我的控制器中,我有这个:
// this block works absolutely perfectly
$course = Course::find(1);
$dates = $course->dates;
$working_date_template = $dates->where('is_template', true)->first();
// this one doesn't work at all and says "call to a member function first() on array"
$broken_date_template = $course->date_template;
在损坏的代码中使用 xdebug 单步执行,$dates = $this->dates 行返回一个空数组,因此之后的所有内容都会中断。
这是 Laravel 访问器/关系系统的限制吗?还是我只是太密集并且做错了什么。
【问题讨论】:
标签: laravel-5 eloquent relationship accessor