通过 author_id 从另一个 table CakePHP 从其他 table 获取用户名
Get Username from other table by author_id from another table CakePHP
我正在使用 CakePHP,但我不知道如何连接来自两个 table 的数据。
这是我的table数据
- 用户
id、用户名、密码 - 等等
- 新闻
id, title, text, author
现在我有了控制器,我在其中执行了从 table news
获取最新消息的操作
$this->set('n_news', $this->News->find('all', array('limit' => 10,'order' => array('News.id DESC'))));
现在我有了这样的数组
array(
(int) 0 => array(
'News' => array(
'id' => '1',
'title' => 'test',
'text' => 'test #1',
'author' => '1',
'date' => '2014-09-25 22:56:55'
)
)
)
现在我想显示作者的用户名(ID 为 1)而不是 id。我怎样才能安全有效地做到这一点?
如果有人能帮助我,那就太好了。这对我未来创建应用程序的计划有很大帮助:)
提前致谢!
使用联接关联这些表:JOIN TABLES
$joins = array(
array(
'table' => 'users',
'alias' => 'User',
'type' => 'INNER',
'conditions' => array('News.auther = User.id'
)
);
$allnews = $this->News->find('all', array('fields'=>array('News.*','User.username as AutherName'),'joins' => $joins,'limit' => 10,'order' => array('News.id DESC')));
$this->set('n_news',$allnews);
我正在使用 CakePHP,但我不知道如何连接来自两个 table 的数据。
这是我的table数据
- 用户
id、用户名、密码 - 等等
- 新闻
id, title, text, author
现在我有了控制器,我在其中执行了从 table news
获取最新消息的操作$this->set('n_news', $this->News->find('all', array('limit' => 10,'order' => array('News.id DESC'))));
现在我有了这样的数组
array(
(int) 0 => array(
'News' => array(
'id' => '1',
'title' => 'test',
'text' => 'test #1',
'author' => '1',
'date' => '2014-09-25 22:56:55'
)
)
)
现在我想显示作者的用户名(ID 为 1)而不是 id。我怎样才能安全有效地做到这一点?
如果有人能帮助我,那就太好了。这对我未来创建应用程序的计划有很大帮助:)
提前致谢!
使用联接关联这些表:JOIN TABLES
$joins = array(
array(
'table' => 'users',
'alias' => 'User',
'type' => 'INNER',
'conditions' => array('News.auther = User.id'
)
);
$allnews = $this->News->find('all', array('fields'=>array('News.*','User.username as AutherName'),'joins' => $joins,'limit' => 10,'order' => array('News.id DESC')));
$this->set('n_news',$allnews);