E
E
EVOSandru62017-08-29 09:20:41
Yii
EVOSandru6, 2017-08-29 09:20:41

How to properly pack a hierarchically merged construction in Yii2 (with or join)?

Good afternoon, there is such a request:
(get products related to the category and its descendants)

$products = Products::findBySql("
            SELECT
                *
            FROM
                m_products
            WHERE
             category_id
            IN (
                SELECT
                    id
                FROM
                    t_products
                WHERE
                    lft >= '{$model->lft}'
                AND
                    rgt <= '{$model->rgt}'
            )
            "
        )->andWhere([
            'exist'=>PublicActiveRecord::EXIST_PUBLIC
        ])->all();

I want to do it more correctly in yii2 without sql?
In theory, you can somehow get a list of category identifiers in an array:
array_merge([$category->id], $category->children()->select('id')->column())
But these are only categories, you need how to get goods.
I'll have to make 1 more request with in
Tell me - how to do it right, maybe through with , relation scope or something else?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
davidnum95, 2017-08-29
@EVOSandru6

$categories = Category::find()
            ->where(['>=', 'lft', $model->lft])
            ->andWhere(['<=', 'rgt', $model->rgt])
            ->with('products')
            ->all();

Connection:
public function getProducts()
    {
        return $this->hasMany(Product::className(), ['category_id' => 'id']);
    }

The array will contain categories with products

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question