问题:
我无法找到使用QueryBuilder构建查询的解决方案(可能首先使用常规SQL查询完成它会有所帮助):
尝试检索用户的所有客户(在其中一个商店用户链接的店铺积分),需要总积分(属于该用户的商店的积分总和)作为虚拟列(能够订购) on),使用paginate()。
数据库结构:
表客户
id email other_fields
1 1@email.com f
2 2@email.com o
3 3@email.com o
表用户
id email other_fields
1 1@user.com b
2 2@user.com a
3 3@user.com r
餐馆
id name other_fields
1 Shop 1 m
2 Shop 1 o
3 Shop 1 o
表user_shops
user_id shop_id
1 1
1 2
3 3
表customer_shop_credits
customer_id shop_id credits
1 1 55
1 2 45
2 2 3
3 3 44
预期结果:
为用户1检索客户时,我希望获得100个积分的客户1和3个积分的客户2
我最近了:
$credits_query = CustomerShopCreditQuery::create()
->useShopQuery()
->useUserShopQuery()
->filterByUserId($user->getId())
->endUse()
->endUse()
;
$customers = CustomerQuery::create()
->addSelectQuery($credits_query, 'credits_alias', false)
->useCustomerShopCreditQuery()
->useShopQuery()
->useUserShopQuery()
->filterByUserId($user->getId())
->endUse()
->endUse()
->endUse()
->withColumn('sum(credits_alias.credits)', 'credits')
->groupById()
->orderBy($order_by_column, $direction)
->paginate($page, $page_size);
导致以下查询:
SELECT customers.id, customers.email, sum(credits_alias.credits) AS credits
FROM customers
CROSS JOIN (
SELECT customer_shop_credits.id, customer_shop_credits.customer_id, customer_shop_credits.shop_id, customer_shop_credits.credits
FROM customer_shop_credits
INNER JOIN shops ON (customer_shop_credits.shop_id=shops.id)
INNER JOIN user_shops ON (shops.id=user_shops.shop_id)
WHERE user_shops.user_id=159
) AS credits_alias
INNER JOIN customer_shop_credits ON (customers.id=customer_shop_credits.customer_id)
INNER JOIN shops ON (customer_shop_credits.shop_id=shops.id)
INNER JOIN user_shops ON (shops.id=user_shops.shop_id)
WHERE user_shops.user_id=159
GROUP BY customers.id
ORDER BY customers.id DESC
LIMIT 25
但是给我的结果有错误的学分。
不确定CROSS JOIN。当我编辑这个查询并使其成为一个JOIN并使用ON (credits_alias.customer_id = customers.id)
作为条件时,学分的总和会更好,但似乎有加倍总和的经典连接问题