Nitish Kumar
Nitish Kumar

Reputation: 6296

Method addEagerConstraints does not exist in Laravel

I'm building a small application on Laravel 5.6 where I'm having a Company model where I am having a hasMany relation to model FinancialAndRisk something like this:

class Company extends Model {

    use SoftDeletes;

    protected $fillable = [
        'name', 'slug', 'establishment', 'parent_id', 'website', 'updates'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'created_at','updated_at','deleted_at'
    ];

    public function financial()
    {
        return $this->hasMany('Noetic\Plugins\Conxn\Models\Company\FinancialAndRisk', 'company_id');
    }

    public function latestFinancial()
    {
        return $this->hasMany('Noetic\Plugins\Conxn\Models\Company\FinancialAndRisk', 'company_id')->latest()->first();
    }

}

Now at some places I want the latest financial report so I made a function latestFinancial

But when in my controller I do something like this:

public function  index()
{
    $companies = Company::with('latestFinancial')->get();

    return response()->json(['companies' => $companies], 200);
}

I get an error:

{
    "message": "Method Illuminate\\Database\\Query\\Builder::addEagerConstraints does not exist.",
    "exception": "BadMethodCallException",
    "file": "D:\\xampp\\htdocs\\conxn\\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Query\\Builder.php",
    "line": 2671,

How can I resolve this.

Upvotes: 0

Views: 7069

Answers (3)

The Billionaire Guy
The Billionaire Guy

Reputation: 3552

The problem for me was that i was using ->get() at the end of the query.

I removed it and my query was fine i.e

formally i did

public function priceCategoryEntities()
{
    return $this->hasOne((new AppUsersVipPriceCategoriesEntity), 'price_category_id', 'id')->get();
}

But Now am using

public function priceCategoryEntities()
{
    return $this->hasOne((new AppUsersVipPriceCategoriesEntity), 'price_category_id', 'id');
}

and the error is gone.

Upvotes: 1

Jonas Staudenmeir
Jonas Staudenmeir

Reputation: 25936

The problem is ->first() because it executes the query. Remove it and use HasOne:

public function latestFinancial()
{
    return $this->hasOne('Noetic\Plugins\Conxn\Models\Company\FinancialAndRisk', 'company_id')->latest();
}

Upvotes: 2

Pol Lluis
Pol Lluis

Reputation: 1162

On your model you should define that you want an eager load with only One result, so instead of saying hasMany you should do hasOne: Also just use ->latest(); first() isn't necessary here

public function latestFinancial()
{
    return $this->hasOne('Noetic\Plugins\Conxn\Models\Company\FinancialAndRisk', 'company_id')->latest();
}

Then it will only give you the latest record associated

Upvotes: 3

Related Questions