1

I have posts and postWriters tables with one-to-many relationships. (I have also writers table).

Each post has been written by several writers collaboratively.

I want to get first 20 posts which have been written by at least one writer I follow.

For example the writers that I follow:

$arrayOfWriterIds_IFollow = [3, 5, 123, 45, ..., 3456] // total 100 ids

The query:

$posts = Post::where(
    array( 'postWriters' => function($l) {
        $l->whereIn('writer_id', $arrayOfWriterIds_IFollow); // or array(3, 5) for 2 writers..
    })
)
->orderBy('submitTimestamp', 'desc')
->take(20)
->get();

The query does not work.

Is this approach appropriate or should I add a dedicated table to evaluate my results?

5
  • How do you follow a writer? Commented Feb 7, 2016 at 15:07
  • I have some tables, one of them is followings table. I get $arrayOfWriterIds_IFollow from this table. Commented Feb 7, 2016 at 15:24
  • display your db structure and models ,there's no need to make 2 different queries for this task you can combine them into 1. Commented Feb 7, 2016 at 16:02
  • There are 3 tables related to question: posts, postWriters and writers. Commented Feb 7, 2016 at 16:06
  • @user2356198 if you expect an answer you would need to display them we cant guess the names of the columns Commented Feb 7, 2016 at 16:16

1 Answer 1

1

If your relationship is defined correctly then the fillowing code should work:

$posts = Post::whereHas('postWriters', function($query) use($arrayOfWriterIds_IFollow) {
    $query->whereIn('writer_id', $arrayOfWriterIds_IFollow);
})
->orderBy('submitTimestamp', 'desc')
->take(20)
->get();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.