简体   繁体   English

当表为空时,Yii查询不返回null

[英]Yii query not returning null when table is empty

I have an empty table tbl_rating that has user_id and post_id columns in it. 我有一个空表tbl_rating,其中包含user_id和post_id列。 In my Post view, I am trying to check to see if the post being viewed has already been rated by the user viewing it. 在我的帖子视图中,我正在尝试查看正在查看的帖子是否已被查看的用户评分。 I'm using the following in the view. 我在视图中使用以下内容。

<?php
$sql='SELECT * FROM tbl_rating WHERE post_id='.$model->id.' AND user_id='.Yii::app()->user->getId().';';
        $connection=Yii::app()->db;
        $command=$connection->createCommand($sql);
        $query=$command->query();
if($query != null):
?>
<p>You've already rated this post.</p>

However, when I view any post, it says "You've already rated this post." 但是,当我查看任何帖子时,它说“你已经评价了这篇文章。” even though there are no ratings. 即使没有评级。 Does the query method return something other than null when it doesn't find any rows in the table? 当查询方法在表中没有找到任何行时,它是否返回null以外的其他内容?

Doing it that way will returns an CDbQueryResult so you need to do 这样做将返回CDbQueryResult,因此您需要这样做

if($query->rowCount !== 0) { }

(see: http://www.yiiframework.com/doc/api/1.1/CDbCommand#query-detail ) (见: http//www.yiiframework.com/doc/api/1.1/CDbCommand#query-detail

I wouldn't recommend doing it that way though. 我不建议这样做。 If you have setup your relations correctly you should be able to do something like 如果你正确设置了你的关系,你应该可以做类似的事情

if($model->rating !== null) { }

See the following for examples on declearing active record relationships: http://www.yiiframework.com/doc/guide/1.1/en/database.arr#declaring-relationship 有关取消活动记录关系的示例,请参阅以下内容: http ://www.yiiframework.com/doc/guide/1.1/en/database.arr#declaring-relationship

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM