Galivan
Galivan

Reputation: 5328

Laravel - get related model

I'm working with code that builds a query that starts with:

$products = \App\Product::where('id', '>', 0);

and then continues to add other related models to $product, depending on which arguments are provided.

I wanted to add a related model to the first line of code. But I'm doing something wrong apparently.

I try to add the "designer" relation by adding: ->get()->designer , like this:

  return json_encode($products = \App\Product::where('id', '>', 0)
        ->get()->designer);

which gives the error: Property [designer] does not exist on this collection instance.

Switching the order doesn't work either: ->designer->get()); (I get Undefined property )

My Product model has the method:

public function designer() {
        return $this->belongsTo('App\Designer');
    }

And the Product table has a "designer_id" column ( it's a "belongsTo" relation so I guess the designer_id should be on the Product model).

The documentation says that : "we can access relationship methods as if they were defined as properties on the model": $comments = App\Post::find(1)->comments;

What am I doing wrong?

Upvotes: 0

Views: 2110

Answers (1)

Thamer
Thamer

Reputation: 1954

  1. $products = \App\Product::where('id', '>', 0) ->get()->designer;

this line of ur code is wrong; I guess ur relationship is one to many which means one designer has many products and one product belongs to one designer.

compared with the example of laravel documentation [comments and post], post has many comments and one comment belongs to one post.

when u execute this line : $products = \App\Product::where('id', '>', 0)->get()

laravel will return to u a collection of products objects witch means u can't get a designer by a collection of products because u have belongsTo relationship inside ur product model.

The solution for ur problem is to use with helper of eloquent like this :

$products = App\Product::with('designer')->where('id', '>', 0)->get();

in laravel community we name this

Eager Loading technique to avoid n+1 requests.

u can find more information here Eager Loading

after that when u want to get designer attributs, u can access to them like this :

   foreach ($products as $product) {
    echo $product->designer->name;
} 

Upvotes: 1

Related Questions