简体   繁体   中英

Laravel 4 - Select rows where count of rows in joined table greater than 0

I need to grab rows of user s where rows of item s exist. Here is my code so far:

$users = DB::table('users')
    ->join('orders', 'orders.user_id', '=', 'users.id')
    ->join('items', 'items.user_id', '=', 'users.id');

How do I add a where condition that will only select user s that have at least one item ?

You don't have to add an extra condition. The query will return results ONLY for the users you have orders and items related with. If you want to return only the users that have items related with, you can drop the join with the orders table (even though I have no idea why you would have user_id in the items table instead of in the orders table).

$users = DB::table('users')->join('items', 'items.user_id', '=', 'users.id');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM