如何遍历从数据库中获取的 yii2 模型

How to loop through yii2 models fetched from the database

我试图遍历从数据库中获取的模型并将结果提供给数据提供者,但似乎不起作用。

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

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

问题似乎出在循环内部; ' $prod->id ' 结果是一个整数。查询 returns 'No results found' 不正确,因为有四个整数匹配 'productId'.

你也可以这样做:

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

现在您有了 ID 数组

//$productposted = [0 =>[1=>1],1=>[2=>2]....]

接下来重建您的查询:

$result =OfferonProduct::find()->where([
   'IN',  'productId', $productposted
])->all();

这样你就有了一个查询和你想要的结果。

使用yii2加入

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