Get records where second relation count is greater than zero

32 Views Asked by At

So I have 3 tables:

categories (id, categoryName)
products (id, categoryID, productName)
types (id, productID, typeName, active). active is boolean

and I need to get all categories and products with active and existing types...

Categories::find()
  ->select('categoryName, productName, products.id')
  ->orderBy('categoryName, productName ASC')
  ->joinWith('products')
  ->asArray()
  ->all()

that gives me all products but i'd need to filter only those product with active and related types... something "where count(types) > 0 and active = 1"

Thanks in advance,

1

There are 1 best solutions below

0
farrusete On

Thanks @barmar. I ended with below code:

Products::find()
  ->select([
    'categories.categoryName',
    'products.productName',
    'products.id',
    'cnt' => Types::find()
      ->select(['COUNT(id)'])
      ->where('productID = products.id AND active = 1')
  ])
  ->orderBy('categoryName, productName ASC')
  ->joinWith('category')
  ->having('cnt > 0')
  ->asArray()
  ->all()