我想用Yii關係創建一個查詢。這是我的關係:爲什麼我不能用yii項目中的關係做這個查詢?
//Articles model
return array(
'articlesHasTags' => array(self::HAS_MANY, 'ArticlesHasTag', 'articles_id',
"with"=>"tag",
),
),
//ArticlesHasTag model
return array(
'articles' => array(self::BELONGS_TO, 'Articles', 'articles_id'),
'tag' => array(self::BELONGS_TO, 'Tag', 'tag_id'),
);
這是查詢:
$blog = Articles::model()->with(array("articlesHasTags"))->findAllByAttributes(array(),array(
"condition"=>"t.del = 0 AND t.active = 1 AND articlesHasTags.tag_id = {$tag->id}",
'order'=>"t.publish_start DESC",
"limit"=>10,
));
之前,我的$tag->id
。
的錯誤信息是:
未知列 'articlesHasTags.tag_id'
我覺得關係很好,因爲我可以使用它,而這個 「articlesHasTags.tag_id = {$tag->id}
」
我改變與表名稱的關係名稱。然後完整的錯誤信息是:
CDbCommand未能執行SQL語句:SQLSTATE [42S22]: 柱未發現:在 1054未知列'articles_has_tag.tag_id 'where子句'。執行的SQL語句是:SELECT
t
。id
ASt0_c0
,t
。active
ASt0_c1
,t
。publish_start
ASt0_c2
,t
。publish_start_local
ASt0_c3
,t
。create_time
ASt0_c4
,t
。last_modify
ASt0_c5
,t
。title
ASt0_c6
,t
。url
ASt0_c7
,t
。short_desc
ASt0_c8
,t
。content
ASt0_c9
,t
。image
ASt0_c10
,t
。comment
ASt0_c11
,t
。hightlight
ASt0_c12
,t
。vote
ASt0_c13
,t
。type
ASt0_c14
,t
。users_id
ASt0_c15
,t
。newspaper_id
ASt0_c16
,t
。del
ASt0_c17
,t
。region_id
ASt0_c18
,t
。language_id
ASt0_c19
,t
。adult
ASt0_c20
,users
。id
ASt1_c0
,users
。t1_c1
,users
。password
ASt1_c2
,users
。author_name
ASt1_c3
,users
。location
ASt1_c4
,users
。last_login
ASt1_c5
,users
。active
ASt1_c6
,users
。remember_me
ASt1_c7
,users
。rank
ASt1_c8
,users
。paypal_acc
ASt1_c9
,users
。url
ASt1_c10
,users
。about_me
ASt1_c11
,users
。image
ASt1_c12
,users
。t1_c13
,users
。t1_c14
,users
。del
ASt1_c15
,users
。admin_active
ASt1_c16
,users
。create_time
ASt1_c17
,users
。first_name
ASt1_c18
,users
。last_name
ASt1_c19
,newspaper
。id
ASt4_c0
,newspaper
。name
ASt4_c1
,newspaper
。create_time
ASt4_c2
,newspaper
。type
ASt4_c3
,newspaper
。active
ASt4_c4
,newspaper
。url
ASt4_c5
,newspaper
。location
ASt4_c6
,newspaper
。newspaper_category_id
ASt4_c7
FROMarticles
t
LEFT OUTER JOINusers
users
ON(t
。users_id
=users
。id
)LEFT OUTER JOINnewspaper
newspaper
ON (t
。newspaper_id
=newspaper
。id
)WHERE(t.del = 0 AND t.active = 1 AND articles_has_tag.tag_id = 42)ORDER BY t.publish_start DESC LIMIT 10
這裏是articles_has_tag表
CREATE TABLE IF NOT EXISTS `articles_has_tag` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`articles_id` int(11) DEFAULT NULL,
`tag_id` int(11) DEFAULT NULL,
`date` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fk_articles_has_tag_tag1_idx` (`tag_id`),
KEY `fk_articles_has_tag_articles1_idx` (`articles_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=93 ;
它的作品! TY! –