如何从另一张桌子获得最受青睐的商品?

时间:2015-08-22 13:36:31

标签: php yii2

所以,有User模型和Item模型。它是一个多对多的关系:一个项目可以属于许多用户,一个用户可以有很多项目。因此,有UserItemRel模型。

总结:

item
 id
 name
 date_created
 date_updated

user
 id
 email
 password
 date_created
 date_updated

user_item_rel
 user_id
 item_id
 date_created

在切换到Yii2之前,我的查询是:

SELECT COUNT(UIR.`user_id`) as `favourited`, IT.`id`, IT.`name`, CA.`name` as `category`
    FROM `user_item_rel` UIR
    LEFT JOIN `item` IT ON UIR.`item_id` = IT.`id`
    LEFT JOIN `category_item` CI ON UIR.`item_id` = CI.`item_id`
    LEFT JOIN `category` CA ON CI.`category_id` = CA.`id`
    WHERE UIR.`date_created` >= (SYSDATE() - INTERVAL 3 YEAR)
    GROUP BY UIR.`item_id`
    ORDER BY
        `favourited` DESC
    LIMIT 20

我已使用yii2-enhanced-gii扩展程序生成模型。

我希望在过去48小时内显示20个最受青睐的物品及其数量。我是从Yii1.1迁移过来的,到目前为止它已经很顺利了,我无法解决这个问题。

我找到了

$this->hasMany(UserItemRel::className(), ['id' => 'user_id'])
                    ->viaTable('user_item_rel', ['id' => 'item_id'], function ($query) {
                        $query->andWhere(['date_created < INTERVAL 2 DAY'])
                        ->orderBy(['COUNT(*)' => SORT_DESC]);
                    });
}

但如何正确使用它?

1 个答案:

答案 0 :(得分:2)

您可以尝试这样的事情:

$items = UserItemRel::find()
    ->asArray()
    ->select("COUNT(`user_id`) as favourited, `item_id`")
    ->groupBy("item_id")
    ->joinWith("item")
    ->orderBy("favourited DESC")
    ->indexBy("item_id")
    ->where("'date_created' >= '".date("Y-m-d", strtotime("-2 days"))."'")
    ->limit(3)
    ->all();

在我的测试中它给了我这样的东西:

Array
(
    [1] => Array
    (
        [favourited] => 4
        [item_id] => 1
        [item] => Array
            (
                [id] => 1
                [name] => Donec
                [date_created] => 2015-08-26
                [date_updated] => 2015-08-26
            )

    )

    [8] => Array
    (
        [favourited] => 3
        [item_id] => 8
        [item] => Array
            (
                [id] => 8
                [name] => Tellus
                [date_created] => 2015-08-26
                [date_updated] => 2015-08-26
            )

    )

    [7] => Array
    (
        [favourited] => 2
        [item_id] => 7
        [item] => Array
            (
                [id] => 7
                [name] => Mollis
                [date_created] => 2015-08-26
                [date_updated] => 2015-08-26
            )

    )

)