databaseactiverecordforeachyii2yii2-model

How to loop through yii2 models fetched from the database


I'm trying to loop through models I fetched from the database and feeding the result to a dataprovider but seems not to work.

        $productposted = Product::find()->where(['userId'=>Yii::$app->user->id])->all();

        foreach($productposted as $prod)
        {
            $query =OfferonProduct::find()->where(['productId'=>$prod->id]);
        }

The problem seems to be inside the loop; ' $prod->id ' result is an integer. The query returns 'No results found' which isn't true since there are four integers matching the 'productId'.


Solution

  • use yii2 join

    $query = OfferonProduct::find()
                    ->select('offeronProduct.*')
                    ->leftJoin('product', '`product`.`id` = `offeronProduct`.`productId`')
                    ->where(['product.userId' => Yii::$app->user->id]);