2017-06-15 111 views
0

我有兩個表的數據庫。一個博客文章和一個與用戶相關的帖子,由發佈表中的user_id字段相關。在我的索引頁上,我有一個帖子的表格,我想添加作者,但是我想顯示用戶的名稱而不是他們的ID。我想作者字段添加到我的帖子物體像這樣的PostsController:如何使用mysql訪問CakePHP中的相關記錄?

public function index() { 
    $this->set('posts', $this->Post->find('all')); 
    foreach ($this as $post){ 
     $post['Post']['author'] = $this->User->findById($post['Post']['user_id']); 
    } 
} 

然而這帶來了,我對NULL調用findById錯誤。我對PHP非常陌生,所以我認爲我對如何使用循環的理解可能不正確。也許有更好的方法不需要循環?

+0

我沒有看到你調用'$ this-> loadModel('User');'使'$ this-> User'可用。你在別的地方做這個嗎? – rickdenhaan

+0

oops是的,我現在已經添加了,現在我在foreach中出現錯誤「無法使用字符串偏移量作爲數組」 – Ben

回答

0

CakePHP中的控制器默認只加載自己的模型。如果您在某個時候需要額外的型號,則需要load it in manually

雖然這並不能解決您的問題,因爲您將find()操作的結果直接設置到視圖中。您需要等待,直到您添加用戶。哦,你通常無法通過$thisforeach迭代,除非你的類實現一個Iterator樣接口(其中控制器不應該有一個理由這樣做)

public function index() { 
    // first load in the User model 
    $this->loadModel('User'); 

    // store the posts in a local variable first 
    $posts = $this->Post->find('all'); 

    // loop through the local variable, also keep the index so we can reference 
    // the post we're modifying 
    foreach ($posts as $index => $post) { 
     $post['Post']['author'] = $this->User->findById($post['Post']['user_id']); 

     // write the modified $post back into the $posts array 
     $posts[$index] = $post; 
    } 

    // **now** you can make $posts available to your view 
    $this->set('posts', $posts); 
} 

一旦此整理出來,read up on linking models together。有一種方法可以設置您的Post型號,以便它將自動填充$post['Post']['author']以及相應的User,而無需手動完成。

0

更好地指定模型中的關係。

在帖子模式初始化後和用戶

public $hasOne = 'User'; 

現在控制器使用之間的關係蘊含()來獲取鏈接模型數據

$posts = $this->Post->find('all')->contain(['User']); 

$this->set('posts', $posts); 

您將得到每一個職位記錄用戶對象,您可以使用獲取用戶名,您不需要編寫單獨的查詢來獲取用戶名。