0
votes

ive got products an articles. An article belongs to a product, so ive got the hasMany-Relationship in my product class and the belongsTo relation in my article class.

Ok now i can grab all articles of a certain product. But what i need is the following:

I want to display only the products which got at least one article. Do i have to use a db-query for that or can i use the eloquent mechanisms for that?

Thanks in advance.

regards

1

1 Answers

1
votes

Take a look at scopes http://laravel.com/docs/eloquent#query-scopes for re-usable where methods. This will allow you to do:

Products::hasArticles()->get();

If you want to perform this on a relation here is an excerpt from http://laravel.com/docs/eloquent#relationships:

If you need to add further constraints to which comments are retrieved, you may call the comments method and continue chaining conditions:

$comments = Post::find(1)->comments()->where('title', '=', 'foo')->first();

So instead of calling Post::find(1)->comments you use the full method comments() to get the query, which will allow you to add your own constraints to it (even a defined scope in the link mentioned above) and retrieve the data via first() or get() etc...