Home > Backend Development > PHP Tutorial > Yii 关联查询有关问题

Yii 关联查询有关问题

WBOY
Release: 2016-06-13 12:04:15
Original
901 people have browsed it

Yii 关联查询问题
三张表 A B C

AB是一对多
BC是一对一

怎么查询满足C的 最终显示 A 的记录
------解决方案--------------------
A---user表(有user_name字段)
B---article表(有user_id字段)
C---article_content表(有article_content_id字段)

条件:通过article_content表的article_content_id字段查询user的username
需要两个relation,在model/Comment.php中加一条:

<br />public function relations() {<br />    return array(<br />        ....<br />        'userInfo' => array(self::BELOGNS_TO, 'User', 'user_id'),<br />    );<br />}<br />
Copy after login


同上,在model/CommentContent.php中添加:
<br />'article' => array(self::HAS_ONE, 'Article', 'article_content_id'),<br />
Copy after login


查询:
<br />$result = ArticleContent::model() -> find('article_content_id = :aid', array(':aid' => $articleId));<br />prinr_r($result -> attributes); // 打印出来的都是article_content表的字段<br />print_r($result -> article -> attributes); //得到article表的字段<br />print_r($result -> article -> userInfo -> user_name); //得到username<br />
Copy after login



我是纯粹为了构造楼主说的这种情况写成这样的哈,一般应该不会设计成这样,多是关联字段都在那个中间表,article表里,查的时候是通过article的model关联其他表查询吧

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template