D
D
Dmitry2020-03-03 11:20:22
Yii
Dmitry, 2020-03-03 11:20:22

How to remake sql query correctly?

Help me remake the sql query correctly for Yii I am
currently using the following query in the controllere:

$query = "SELECT * FROM products_related JOIN products ON products.id = products_related.related_id WHERE products_related.product_id = 2";


I'm trying to change it to a query like this:

//$relatedss = RelatedAssignment::find()
        ->select('*')
        ->leftJoin('products', '`products.id` = `products_related`.`related_id`')
        ->where(['products_related.product_id' => 1])
        ->all();


Tell me where am I making a mistake?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Bay, 2020-03-03
@JoneCode

First set up links https://github.com/yiisoft/yii2/blob/master/docs/g... (hasOne, hasMany).
Then your request will look like this:

RelatedAssignment::find()->andWhere(['products_related.product_id' => 1])
->with(['products']) // опционально, читайте про жадную загрузку        
->all();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question