0

I need to be able to specify conditions on a relationship (one-to-many).

Example being; We have a Post which has many Comments, but I only want the Posts with Comments made by User A and then return the Post object(s).

The only way I can currently think of doing this is with a Fluent query, which wouldn't return the Post object I desire!

EDIT:

The comment has to of been made by User A. The relationship of the User who made the Comment to Post isn't a direct one. It would go through the Comment table.

RE EDIT:

Would it also be possible to say have distinct Posts? Rather than return 3 of the same Post Object?

1
  • you can try this $post=Posts::with('comments')->where('user_id','=',$user_id)->get() this will return with data from post and comments table only for particular user Commented Aug 22, 2013 at 9:43

1 Answer 1

7

You can query relationships. You would end up with something like this:

$postsWithComments = $user->posts()->has('comments', '>=', 1)->get(); 

Here is an extract from documentation: http://laravel.com/docs/eloquent

Querying Relations

When accessing the records for a model, you may wish to limit your results based on the existence of a relationship. For example, you wish to pull all blog posts that have at least one comment. To do so, you may use the has method:

Checking Relations When Selecting

$posts = Post::has('comments')->get(); 

You may also specify an operator and a count:

$posts = Post::has('comments', '>=', 3)->get(); 
Sign up to request clarification or add additional context in comments.

8 Comments

OP wants to filter the Posts so he only gets those with Comments made by a specific User.
This should do what expected then.
Well it was straight out from documentation. You have to be able to learn from these kind of examples. In any case I added an example of how it might look like in the end.
Yeah, as said by @cuewizchris I need the one's made by a specific User. Editting original post.
Already covered that with the first code example. ;) Good luck in your project. @cuewizchris thanks :)
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.