【问题标题】:Using an Eloquent relationship within an Eloquent accessor?在 Eloquent 访问器中使用 Eloquent 关系?
【发布时间】: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


    【解决方案1】:

    我刚刚解决了这个问题。

    我需要在模型本身中使用$this->dates(),因为这会返回关系,然后我可以使用where() 方法和其他查询构建器方法将其过滤掉。

    这当然是在 Laravel 文档中提到的 - 我只是没有发现它。

    【讨论】:

      猜你喜欢
      • 2015-11-22
      • 1970-01-01
      • 2020-07-03
      • 2017-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-09
      • 2015-06-27
      相关资源
      最近更新 更多