Kombuwa
Kombuwa

Reputation: 1651

How to do Laravel ORM subquery

How can I do the sql below in laravel ORM.

select * from comments where page_id in (
    select id from pages where pages.user_id = "kombuwa"
)

Upvotes: 1

Views: 150

Answers (2)

Pillai Manish
Pillai Manish

Reputation: 71

Thought the above answer, is right, I think it would be helpful if you use the relational model concept. Then, you can just simply use the Laravel Eloquent ORM. Like for example, in your case I think it is like, one page has many comments. So, you can just add the relation (in case of Laravel just add the function in the required model), and that makes your query easier.

Then, your query will look like :

Pages::where('user_id','kombuwa')->comments

What Laravel does here is that it finds the pages with user id kombuwa, and then finds all the comments of that page.

For more details on Laravel Relation check this link, you will get more details.

Hope it helps, though late to actual question. Thank You :)

Upvotes: 1

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111829

You can do it this way:

$userId = 'kombuwa';
$comments = DB::table('comments')->whereIn('page_id', function($q) use ($userId) {
   $q->select('id')->from('pages')->where('pages.user_id', $userId);
})->get();

(I moved $userId to variable just in case you want to use it from input for example)

Upvotes: 2

Related Questions