R
R
Ruslan Ruslanov2018-09-20 09:18:03
Yii
Ruslan Ruslanov, 2018-09-20 09:18:03

YII2 How to correctly build a query with joinWith?

The bottom line: I get $id, I find it in the product_image table 'id' => $id, and I also need a record from the table product, which should have 'id' => 'product_image->id'. You need to find one picture record and one product record.
How to arrange it?
Did it like this:

$model = Images::find()
            ->joinWith('products')
            ->where(['id' => $id])
            ->andWhere(['id' => 'product_id'])
            ->one();

but it looks like something is wrong.
I think you can make 2 requests, but then what's the point of joinWith?
Can I do without the second request and how to arrange it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Ruslan Ruslanov, 2018-10-05
@dasauser

$model = Images::find()
        ->joinWith('product')
        ->where(['product.id' => $id])
        ->asArray()
        ->one();

V
vyrkmod, 2018-09-20
@vyrkmod

Obviously, the image-product connection is not described, otherwise the product would not be "got" through Products::find(), but like $model->product. Here is the detail. In your case you need something like

class Images extends ActiveRecord
{
    // ...

    public function getProduct()
    {
        return $this->hasOne(Products::className(), ['id' => 'product_id']);
    }
}

UPD: for eager loading we use the with() method and not joinWith(), the latter is for manual query assembly.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question