
php mysql 读取用户收藏内容
用户收藏功能
网站具有用户收藏功能,涉及三个数据表:
favorites(收藏数据)
立即学习“PHP免费学习笔记(深入)”;
goods(商品)
articles(文章)
读取收藏标题
需要根据收藏记录中的 cid 读取收藏的文章或商品的标题。有两种方法:
第一种方法:foreach 循环
$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 循环性能较好。对于大量数据,数组存储方法性能更好。
以上就是PHP+MySQL如何高效读取并排序用户收藏的商品和文章标题?的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号