mercredi 2 mai 2018

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?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2wbRKqe
via IFTTT

Aucun commentaire:

Enregistrer un commentaire