我有一个现有的sqlalchemy对象,我生成了sql(postgres)
class Category(Model, BaseNestedSets):
id = Column(Integer, primary_key=True)
name = Column(String(400), index=True, unique=False)
image = Column(ImageColumn(thumbnail_size=(30, 30, True), size=(300, 300, True)))
products = relationship("Catalog", backref='categs')
# TODO do a multi-joins and filter in order to fetch sizes and colors from categories.
@classmethod
def get_parents_list(cls, db, category_id):
beginning_getter = db.session.query(cls).filter(cls.id == category_id).cte(name='parent_for', recursive=True)
with_recursive = beginning_getter.union_all(db.session.query(cls).filter(cls.id == beginning_getter.c.parent_id))
return db.session.query(with_recursive)
有了这个,我有以下SQL查询: 对查询的其他修改由星号
括起如何实现新的sqlalchemy对象?我应该添加什么?
WITH RECURSIVE children_for (rgt,
lft,
id,
name,
image,
parent_id,
LEVEL,
tree_id)
AS (
SELECT
category.rgt AS rgt,
category.lft AS lft,
category.id AS id,
category.name AS name,
category.image AS image,
category.parent_id AS parent_id,
category.level AS LEVEL,
category.tree_id AS tree_id
FROM
category
WHERE
category.id = 122
UNION ALL
SELECT
category.rgt AS category_rgt,
category.lft AS category_lft,
category.id AS category_id,
category.name AS category_name,
category.image AS category_image,
category.parent_id AS category_parent_id,
category.level AS category_level,
category.tree_id AS category_tree_id
FROM
category,
children_for
WHERE
category.parent_id = children_for.id
)
SELECT *DISTINCT*
children_for.rgt AS children_for_rgt, children_for.lft AS children_for_lft, children_for.id AS children_for_id, children_for.name AS children_for_name, children_for.image AS children_for_image, children_for.parent_id AS children_for_parent_id, children_for.level AS children_for_level, children_for.tree_id AS children_for_tree_id
FROM
children_for *JOIN catalog cat ON children_for.id = cat.category_id*