Y
Y
Yariy2021-02-04 14:10:50
Laravel
Yariy, 2021-02-04 14:10:50

Why does the Call to undefined method Illuminate\Database\Eloquent\Relations\BelongsTo::stores() error occur?

There are two models: warehouse and branch.
A branch can have many warehouses. Accordingly, the Branch in the model has

public function stores(){
        return $this->hasMany('App\Store');
    }

At the warehouse:
public function branch()
    {
        return $this->belongsTo('App\Branch');
    }

But for some reason, if I call at the warehouse
public function getStoresOfParentBranch(){
        return $this->branch()->stores();
    }

Error Call to undefined method Illuminate\Database\Eloquent\Relations\BelongsTo::stores()

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
Georgy Eremeev, 2021-02-04
@Yariy

Because it $this->branch()issues \Illuminate\Database\Eloquent\Relations\BelongsTo, not the model

J
jazzus, 2021-02-04
@jazzus

So no one causes a relationship. There are a lot of problems with this getStoresOfParentBranch method. From thousands of identical queries to the database to errors.
It's right to do so.
If the relation is called once, then we write immediately in the controller / template.
$store->branch->stores;
But NOT in the model.
If cycles or collections of json resources are planned, or simply > 1 relationship calls, then we first chain through with

Store::with('branch.stores')
    ->get();

and then use $store->branch->stores without queries to the database, no matter how many elements in the collection are. Although I would do it differently. But I will not ship. For starters, it's enough to get rid of getStoresOfParentBranch before it's too late.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question