Reputation: 97
I'm using CakePHP and i don't know how to connect data from two tables.
Here is my tables data
id, username, password - and so on
id, title, text, author
Now i have controller, in which I have action which gets latest news from table news
$this->set('n_news', $this->News->find('all', array('limit' => 10,'order' => array('News.id DESC'))));
And now i have array which looks like this
array(
(int) 0 => array(
'News' => array(
'id' => '1',
'title' => 'test',
'text' => 'test #1',
'author' => '1',
'date' => '2014-09-25 22:56:55'
)
)
)
And now i want to display username of author (with ID 1) instead of id. How can i do it in secure and efficient way?
It would be awesome if anyone can help me. This will help me a lot in my future plans for creating my application :)
Thanks in advance!
Upvotes: 1
Views: 246
Reputation: 4142
Use join to relate these tables : 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);
Upvotes: 1