问题
我正在尝试创建一个网站,用户可以发布帖子,然后他们的朋友可以看到这些帖子。与facebook,twitter等相似
我达到了用户可以成为朋友并且可以发布内容的程度。但是,我坚持将显示的帖子限制在用户的朋友帖子中。目前,每个用户都可以看到每个帖子
我在MVC架构中使用PDO。
数据库结构
TABLE `friends` (
`friendship_id` int(11) NOT NULL AUTO_INCREMENT,
`user_one` int(11) NOT NULL,
`user_two` int(11) NOT NULL,
PRIMARY KEY (`friendship_id`),
FOREIGN KEY (user_one) REFERENCES users(user_id),
FOREIGN KEY (user_two) REFERENCES users(user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
TABLE `posts` (
`post_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`post_text` text NOT NULL,
`user_id` int(11) unsigned NOT NULL,
PRIMARY KEY (`post_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
模型
/**
* Get all posts from the suer's friends
* @return array an array with several objects (the posts)
*/
public static function getAllPosts()
{
$my_id = Session::get('user_id');
$database = DatabaseFactory::getFactory()->getConnection();
// get all of the user's friends
$friends = $database->prepare("
SELECT user_one FROM friends WHERE user_two = '$my_id';
SELECT user_two FROM friends WHERE user_one = '$my_id';
");
$query = $database->prepare("SELECT post_text FROM posts WHERE user_id = '$my_id' OR user_id = '$friends'");
$query->execute(array());
return $query->fetchAll();
}
控制器
/**
* Gets all posts (of the user and his friends).
*/
public function index()
{
$this->View->render('post/index', array(
'posts' => PostModel::getAllPosts()
));
}
视图
<?php if ($this->posts) { ?>
<?php foreach($this->posts as $key => $value) { ?>
<p><?= htmlentities($value->post_text); ?></p>
<?php } ?>
<?php } ?>
错误讯息
PDOStatement类的对象无法转换为 PostModel.php
中的字符串
目标
只显示自己和朋友的帖子。不显示用户帖子,我不是朋友。
更新
更新的模型(感谢您提供有用的评论!)
/**
* Get all posts from the suer's friends
* @return array an array with several objects (the posts)
*/
public static function getAllPosts()
{
$my_id = Session::get('user_id');
$database = DatabaseFactory::getFactory()->getConnection();
// get all of the user's friends
$friendsQuery = $database->prepare("
SELECT user_one FROM friends WHERE user_two = '$my_id';
SELECT user_two FROM friends WHERE user_one = '$my_id';
");
$friendsQuery->execute();
$friends = $friendsQuery->fetchAll();
$query = $database->prepare("SELECT post_text FROM posts WHERE user_id = '$my_id' OR user_id = '$friends'");
$query->execute(array());
return $query->fetchAll();
}
新错误消息
PDOStatement :: execute():SQLSTATE [HY000]:一般错误:2014年不能 在其他未缓冲的查询处于活动状态时执行查询。