[英]Selecting from table in different controller in cakephp
在我的“用戶”控制器中,我試圖在其個人資料中顯示給定用戶的帖子。 我該怎么做? 基本上,我在Users控制器中嘗試訪問Posts表
這些是我的桌子
//Posts
id | body | user_id
//Users
user_id | username
這是我的用戶個人資料功能
UsersController.php
public function profile($id = null) {
$this->User->id = $id;
if (!$this->User->exists()) { //if the user doesn't exist while on view.ctp, throw error message
throw new NotFoundException(__('Invalid user'));
}
$conditions = array('Posts.user_id' => $id);
$this->set('posts', $this->User->Posts->find('all',array('conditions' => $conditions)));
}
/Posts/profile.ctp
<table>
<?php foreach ($posts as $post): ?>
<tr><td><?php echo $post['Post']['body'];?>
<br>
<!--display who created the post -->
<?php echo $post['Post']['username']; ?>
<?php echo $post['Post']['created']; ?></td>
</tr>
<?php endforeach; ?>
</table>
我在參考profle.ctp的每一行時都遇到了幾個“未定義的索引錯誤”
Undefined index: Post [APP/View/Users/profile.ctp, line 11]
在您的profile
操作上的UsersController
,您可以使用User
模型訪問關聯的信息。
例:
class UsersController extends AppController {
public function profile($id = null) {
$this->User->recursive = 2;
$this->set('user', $this->User->read(null, $id));
}
}
在User
和Post
模型中,您應該具有正確的關聯設置:
User
模型:
class User extends AppModel {
public $hasMany = array('Post');
}
Post
模型:
class Post extends AppModel {
public $belongsTo = array('User');
}
現在,您將在視圖中的$user
變量上看到具有指定配置文件ID的所有用戶數據,以及該用戶的關聯帖子。
CakePHP文檔中的此頁面提供了一些非常有用的提示,可幫助您從模型中讀取數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.