【问题标题】:Laravel blade relationships using models使用模型的 Laravel 刀片关系
【发布时间】:2018-06-18 23:38:28
【问题描述】:

我在这三个模型之间有关系

class Teach extends Model {

public function departments() {
    return $this->belongsToMany('App\Department', 'teach', 'id', 'department_id');
}

public function subjects() {
    return $this->belongsToMany('App\Subject', 'teach', 'id', 'subject_id');
}

public function teachers() {
    return $this->belongsToMany('App\Teacher', 'teach', 'id', 'teacher_id');
} 
}

我想使用这些关系列出特定教师的所有部门和科目我在我看来已经尝试过,但它不起作用 $teacher->teach->部门;

【问题讨论】:

  • 好吧,这是你的 Teach 模型,而不是 Teacher(你写了你想在视图中显示教师),你没有包含你的视图并且你没有包含你得到的错误
  • 试试这个:$teacher->teach()->departments

标签: php laravel


【解决方案1】:

这是教师和部门之间的多对多关系

class Teacher extends Model {

  public function departments() {
    return $this->belongsToMany('App\Department', 'teach', 'teacher_id', 'department_id');
  }

}


class Department extends Model {

  public function teachers() {
    return $this->belongsToMany('App\Teacher', 'teach', 'department_id', 'teacher_id');
  }

}

现在获取数据

$teacher = Teacher::with('departments')->find(1);
$departments = $teacher->departments;

【讨论】:

    猜你喜欢
    • 2016-12-19
    • 1970-01-01
    • 2021-08-10
    • 2013-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-09
    相关资源
    最近更新 更多