用户收藏功能
网站具有用户收藏功能,涉及三个数据表:
-
favorites(收藏数据)
立即学习“PHP免费学习笔记(深入)”;
-
goods(商品)
- id
- title
-
articles(文章)
- id
- title
读取收藏标题
需要根据收藏记录中的 cid 读取收藏的文章或商品的标题。有两种方法:
$favorites = $collection->find(array(), array('sort' => array('dateline' => -1))); foreach ($favorites as $favorite) { if ($favorite['type'] == 1) { $goods = $goodscollection->findbyid($favorite['cid']); echo $goods['title']; } else { $article = $articlescollection->findbyid($favorite['cid']); echo $article['title']; } }
第二种方法:数组存储
$goodsids = $goodscollection->find( ['id' => ['$in' => $favoritecids]], ['id' => 1, 'title' => 1, '_id' => 0]) ->toarray(); $articleids = $articlescollection->find( ['id' => ['$in' => $favoritecids]], ['id' => 1, 'title' => 1, '_id' => 0]) ->toarray();
对标题排序
为了按照 favorites 表中的 dateline 排序标题,可以使用以下联表查询:
SELECT IF(goods.id IS NULL, articles.title, goods.title), favorites.* FROM favorites LEFT JOIN goods ON goods.id = favorites.cid AND favorites.type = 1 LEFT JOIN articles ON articles.id = favorites.cid AND favorites.type = 2 ORDER BY dateline DESC
性能考虑
对于少量数据,foreach 循环性能较好。对于大量数据,数组存储方法性能更好。