Eloquent致命错误:在第451行的\ illuminate \ database \ Eloquent \ Builder.php中调用未定义的方法Eloquent \ Collection :: addEagerConstraints()

时间:2016-09-13 18:39:44

标签: php laravel laravel-4 eloquent

我正在关注tutorial,您可以在其中保存关系,以确定用户是否是其他用户的朋友,反之亦然。

就我而言,我需要在关系表boundTogether_projects中保存绑定在一起的项目。

所以在Project.php模型中我创建了以下Eloquent关系:

<?php
    /*** Bound together projects ***/
    public function projectsBoundToThisOne(){
        return $this->belongsToMany('Models\User\Project', 'boundTogether_projects', 'bound_id', 'project_id');
    }
    public function boundTo(){
        return $this->belongsToMany('Models\User\Project', 'boundTogether_projects', 'project_id', 'bound_id');
    }
    public function boundTogetherProjects(){
        return $this->projectsBoundToThisOne()->wherePivot('bound',true)->get()->merge($this->boundTo()->wherePivot('bound', true)->get());
    }

这不起作用,因为我收到以下错误:

  

致命错误:调用未定义的方法   Illuminate \ Database \ Eloquent \ Collection :: addEagerConstraints()in   第451行\ illuminate \ database \ Eloquent \ Builder.php

当我将此方法称为急切加载时,看起来问题就出现了。也就是说:

$projects = Project::with('boundTogetherProjects');

Eloquent版本是5.1

我错过了什么?我该如何解决?

1 个答案:

答案 0 :(得分:1)

这可能是因为boundTogetherProjects不是关系方法。简单地从关系中获取一些数据并将其合并到另一个。所以有效的方法是:

$projects = Project::with('projectsBoundToThisOne','boundTo');

然后对于每个项目,您可以运行boundTogetherProjects来获取项目

$projects->each(function($project) {
  dd($project->boundTogetherProjects());
});