CakePHP执行此类查询的方式是什么?
SELECT news.* FROM news, users
INNER JOIN news_users nu ON nu.user_id = users.id
WHERE users.id = $user_id
我有一个链接表news_users
,因此尝试$news = $this->News->findByUserId($this->User->id);
之类的内容无效,因为它会查找news.user_id
P.S。上面的查询有效,我只想缩短脚本。
答案 0 :(得分:1)
您可以在新闻模型中声明 findByUserId 功能:
//put this code in your News model
public function findByUserId($user_id = null)
{
return $this->find('all', array(
'conditions' => array(
'NewsUser.user_id' => $user_id
),
'joins' => array(
array(
'table' => 'news_users',
'alias' => 'NewsUser',
'type' => 'INNER',
'conditions' => array(
'NewsUser.news_id = News.id'
)
)
)
));
}
然后你可以在 NewsController
中使用你的findByUserId函数//this code in NewsController
$news = $this->News->findByUserId($this->User->id);