I currently have a users
table and a posts
table. My posts table has a field for user_id
, however, I am not sure how I would grab the users name
field which is in the users
table. I was thinking of using the models afterFind()
method and then using SQL to select the data, but there has to be a better way than this. Also, on my view action, I am using the read()
function to grab a single post. Would the models afterFind()
kick in after it runs read()
? If not, is there an equivalent such as afterRead()
?
Asked
Active
Viewed 76 times
0

Strawberry
- 66,024
- 56
- 149
- 197
3 Answers
2
Just make an association of Post belongsTo User, and every regular find/read operation that has a sufficiently high recursive
value will automatically fetch the user with each post.
$post = $this->Post->find(...);
echo $post['User']['name'];

deceze
- 510,633
- 85
- 743
- 889
-
I'd use `echo h($post['User']['name'])` - for security reasons! always escape your output. – mark Mar 05 '12 at 12:27
-
Interesting, I have never heard of output escaping. I have only heard of input escaping, but I guess it makes sense. However, if I had tight restrictions on my input then I wouldn't need to escape for output right? – Strawberry Mar 05 '12 at 19:37
-
1@Doug Always escape all user-supplied values, period. Unless you're reformatting it into something guaranteed harmless, like `(int)$val` or `date('Y-m-d', $date)`. – deceze Mar 05 '12 at 23:42
-
Should it be escaped in the model or view? Also, what if I am pulling multiple things from the database? Does that mean I have to escape everything? I can just escape `h($post)` instead of the more specific right? – Strawberry Mar 06 '12 at 02:38
-
1@Doug Escape on output. See http://stackoverflow.com/questions/9512873/is-it-better-to-escape-encode-the-user-input-before-storing-it-to-database-or-to/. And yes, you'll have to escape every individual value, at least by looping over them. Security doesn't come for free. – deceze Mar 06 '12 at 03:14
0
you have to go like below :
$this->Cake->findById(7); Cake.id = 7
here , you can you use your user_id instead of 7 like..

NovusMobile
- 1,813
- 2
- 21
- 48
0
$this->Post->bindModel(array('belongsTo'=>'User'));
$post = $this->Post->findById($post_id);
$userName = $post['User']['name'];
Here are errors, I've typed it in eclipse (:

sukinsan
- 513
- 3
- 14