MySQL:向当前用户

时间:2016-09-04 14:51:17

标签: php mysql cakephp-3.0

我想听听你的意见,哪些是最好的方法来做这些我在标题中简要解释。

基本上我在主页上显示了一些帖子,这些帖子可以被用户喜欢或淹没。因此,我的意图是在此Feed中显示用户之前是否喜欢此帖子。

Supouse这是我的主要表格

Table 'posts'
-------------
id
title
content
tags

Table 'likes'
-------------
user_id
post_id
date

这是我在主页上的主要查询

SELECT * FROM posts LIMIT 20

如果current_user()之前喜欢每个帖子,我如何在此查询中包含?我是否需要执行separe查询?

谢谢你们!

编辑:我不希望用户喜欢过滤查询,只想在每个帖子中输入一个布尔值,表示当前用户是否喜欢每个帖子!

2 个答案:

答案 0 :(得分:1)

您可以通过两种方式解决此任务:一个带连接的查询和两个单独的查询。您应该测试性能并选择最佳方法。

第一个解决方案:

SELECT posts.* FROM posts 
INNER JOIN likes on posts.id=likes.post_id 
WHERE likes.user_id='<user id of current user >' LIMIT 20

第二个解决方案

SELECT post_id 
FROM likes 
WHERE user_id='<user id of current user >' 
LIMIT 20

SELECT * FROM posts 
WHERE id in (<list of ids from the first query>)

评论解决方案:

SQL

SELECT posts.*, likes.user_id as liked FROM posts 
LEFT JOIN likes on posts.id=likes.post_id and likes.user_id='<user id of current user >'
LIMIT 20

PHP

foreach($rows as $row) {
   if ($row['liked']) {
       //do something
   }
}

答案 1 :(得分:0)

使用CakePHP3的解决方案

// Posts Model
$this->hasMany ('Likes', [
    'joinType' => 'LEFT',
    'propertyName' => 'favs'
]);

// the query
$this->Posts
    ->find('all')
    ->contain([
       'Likes' => [
           'conditions' => array('Likes.user_id' => <user id>)
       ]
    ]
);
相关问题