【问题标题】:How to loop through yii2 models fetched from the database如何遍历从数据库中获取的 yii2 模型
【发布时间】:2021-04-02 15:48:41
【问题描述】:

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

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

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

问题似乎在循环内部; ' $prod->id ' 结果是一个整数。查询返回“未找到结果”,这是不正确的,因为有四个整数与“productId”匹配。

【问题讨论】:

  • 您应该先学习查询构建器和gridview / dataprovider以便更好地理解。

标签: database activerecord foreach yii2 yii2-model


【解决方案1】:

你也可以这样做:

$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();

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

【讨论】:

    【解决方案2】:

    使用 yii2 加入

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-13
      • 2019-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-14
      • 2023-04-09
      • 1970-01-01
      相关资源
      最近更新 更多