我有以下 SQL 查询
SELECT
i.id,
i.title,
i.slug,
i.date_added as date_added,
a.slug as area_slug,
COUNT(o.id) as offers,
COUNT(v.item_id) as total_item_views
FROM
`item` `i`
LEFT JOIN
`offer` `o`
ON
i.id=o.item_id
LEFT JOIN
`viewed_item` `v`
ON
i.id=v.item_id
INNER JOIN
`a` `a`
ON
a.id=i.area_id
WHERE
j.id=3
它在 PHPMyAdmin 中运行良好。我将它转换为 Yii,所以它看起来像这样:
$cmd = Yii::app()->db->createCommand();
$cmd->select(array('i.id, i.title, i.slug, i.date_added as date_added, a.slug as area_slug, COUNT(o.id) as offers, COUNT(v.item_id) as total_item_views'));
$cmd->from('item as i');
$cmd->leftJoin('offers as o', 'i.id=o.item_id');
$cmd->leftJoin('viewed_item as v', 'i.id=v.item_id');
$cmd->join('area as a', 'a.id=i.area_id');
$cmd->where('i.id=:id', array(':id'=>$id));
$basicStatModel = $cmd->query();
这适用于“viewed_item”表的记录等于用于此查询的 $id 值的情况。当前viewed_item只有2条记录,但它们在item表中是多条记录。我正在查看我的堆栈,它显示了这一点:
ViewedItem.findByPk()
查询 SQL: SELECT * FROM viewed_item
t
WHERE t
。id
='3' 限制 1
目前该表中没有 ID 等于 3,所以我猜这就是页面错误的原因。但与此同时,我不确定它为什么要在该表中查找 ID 值。我可以看到它正在使用 findByPK() 方法。但是我已经要求它在 SQL 语句中找到本质上的 FK。
我该如何解决这个问题?SQL 在 PHPMyAdmin 内部工作,这让我很震惊。