我正在尝试创建一种关系,以通过名为成绩的模型访问名为评论的表,该模型通过成绩中的学生加载
Grade 和 Student 模型都属于另一个
根据我的理解,无法访问需要数据透视表的 hasManyThrough 关系(评论没有成绩标识符,只有学生标识符)
class Grade extends Model{
public function comments(){
return $this->hasManyThrough("App\Comment","App\Student");
}
}
Run Code Online (Sandbox Code Playgroud)
我为 Laravel 4 @ HasManyThrough找到了这些具有一对多关系的函数,但它给了我错误Class 'App\Illuminate\Database\Eloquent\Relations\HasMany' not found
我对命名空间没有很好的理解,也无法弄清楚我应该在 Laravel 5 的位置做什么。
public function getCommentsAttribute()
{
if ( ! array_key_exists('comments', $this->relations)) $this->loadComments();
return $this->getRelation('comments');
}
protected function loadComments()
{
$comments = Comment::join('grade_student', 'comments.student_id', '=', 'grade_student.student_id')
->where('grade_student.grade_id', $this->getKey())
->distinct()
->get(['comments.*','grade_id']);
$hasMany = new Illuminate\Database\Eloquent\Relations\HasMany(Translation::query(), $this, 'grade_id', 'id');
$hasMany->matchMany(array($this), $comments, 'comments');
return $this;
}
Run Code Online (Sandbox Code Playgroud)
评论表
Schema::create('comments', function (Blueprint …Run Code Online (Sandbox Code Playgroud)