Eloquent Fatal error: Call to undefined method Eloquent\Collection::addEagerConstraints() in \illuminate\database\Eloquent\Builder.php on line 451

自作多情 提交于 2019-12-12 02:22:24

问题


I am following a tutorial where you can save relationships in one table to determine if a user is friend of another user and viceversa.

In my case, I need to save in a relational table boundTogether_projects those projects that are bound together.

So inside the Project.php Model I created the following Eloquent relationships:

<?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());
    }

This is not working, since I get the following error:

Fatal error: Call to undefined method Illuminate\Database\Eloquent\Collection::addEagerConstraints() in \illuminate\database\Eloquent\Builder.php on line 451

Looks like the problem comes right when I call this method as eager loading. That is to say:

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

The Eloquent version is 5.1

What am I missing? How do I fix it?


回答1:


This is probably because boundTogetherProjects is not relationship method. It simple gets some data from relationship merged to the other. So the valid way would be:

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

and then for each project you could run boundTogetherProjects to get the projects

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


来源:https://stackoverflow.com/questions/39476928/eloquent-fatal-error-call-to-undefined-method-eloquent-collectionaddeagercons

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!