如何循环使用从数据库中提取的yii2模型



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

$productposted = Product::find()->where(['userId'=>Yii::$app->user->id])->all();
foreach($productposted as $prod)
{
$query =OfferonProduct::find()->where(['productId'=>$prod->id]);
}

问题似乎在循环内部$prod->id的结果是一个整数。查询返回"未找到结果",这不是真的,因为有四个整数与"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]);

最新更新