У меня есть запрос БД, который выглядит как
SELECT f.forum_id,
t.topic_id,
MAX(p.post_id) AS `maxpostid`,
p.admin_user_id,
p.user_id,
t2.topicscount,
SUM(Maxp.postcount) AS postscount,
CONCAT(au.firstname,' ',au.lastname) AS adminname,
fu.nick_name AS nickname,
CONCAT(ce1.value,' ',ce2.value) AS fullname
FROM my_forum AS f
LEFT JOIN my_topic AS t
ON f.forum_id = t.forum_id
LEFT JOIN
(SELECT topic_id,
MAX(post_id) AS post_id,
COUNT(*) AS postcount
FROM my_post
GROUP BY topic_id
) AS Maxp
ON Maxp.topic_id = t.topic_id
LEFT JOIN my_post AS p
ON p.post_id = Maxp.post_id
LEFT JOIN admin_user AS au
ON au.user_id = p.admin_user_id
LEFT JOIN my_user AS fu
ON fu.user_id = p.user_id
LEFT JOIN customer_entity_varchar AS ce1
ON ce1.entity_id = p.user_id
AND ce1.attribute_id = 1
LEFT JOIN customer_entity_varchar AS ce2
ON ce2.entity_id = p.user_id
AND ce2.attribute_id = 2
LEFT JOIN
(SELECT forum_id, COUNT(*) AS topicscount
FROM my_topic
GROUP BY forum_id
) AS t2
ON t2.forum_id = f.forum_id
WHERE forum_status = '1'
GROUP BY f.forum_id
Я хочу написать его с помощью коллекции magento или преобразовать пользовательский запрос в коллекцию, возможно ли это?
Я не знаю, как писать соединения, как
LEFT JOIN
( SELECT topic_id,
MAX(post_id) AS post_id,
COUNT(*) AS postcount
FROM my_post
GROUP BY topic_id
) AS Maxp
ON Maxp.topic_id = t.topic_id
в пурпурном,
потому что magento написать присоединяется как
$col->getSelect()->join(array('t' => 'topic'),'main_f.forum_id = t.forum_id');
как написать это с подзапросом?
Спасибо
Я не тестировал этот код, но он должен выглядеть примерно так:
$subquery = new Zend_Db_Expr('SELECT my_post.topic_id, MAX(my_post.post_id) AS post_id, COUNT(*) AS postcount FROM my_post GROUP BY my_post.topic_id');
$collection->getSelect()->joinLeft(array('t' => 'topic'), 'Maxp.topic_id = t.topic_id', array('Maxp' => $subquery));
В Magento2 напишет подзапрос как
$subquery = new \Zend_Db_Expr('SELECT my_post.topic_id, MAX(my_post.post_id) AS post_id, COUNT(*) AS postcount FROM my_post GROUP BY my_post.topic_id');
$sql = $collection->getSelect()->from(array('f' => 'my_forum'), array('f.forum_id'));
$sql->columns(array('Maxp' => $subquery));
//to debug
$sql->__toString();exit;