簡體   English   中英

如何使用MySQL訪問CakePHP中的相關記錄?

[英]How to access related record in CakePHP with mysql?

我有兩個表的數據庫。 一個帶有博客帖子,另一個帶有用戶,由發布表中的user_id字段關聯。 在我的索引頁面上,我有一張帖子表,我想向其中添加作者,但是我想顯示用戶名而不是其ID。 我正在嘗試在PostsController中向我的發布對象添加一個author字段:

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很陌生,所以我認為我對如何使用循環的理解可能不正確。 也許有一種不需要循環的更好的方法?

默認情況下,CakePHP中的控制器僅加載自己的模型。 如果您在某個時候需要其他模型,則需要手動加載

但是,那並不能解決您的問題,因為您將直接將find()操作的結果設置到視圖中。 您將需要等待,直到將用戶添加到其中。 哦,通常您不能使用foreach遍歷$this ,除非您的類實現了類似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);
}

整理之后, 請繼續閱讀將模型鏈接在一起的內容 有一種方法可以設置您的Post模型,這樣它將自動用相應的User填充$post['Post']['author'] ,而無需您手動進行操作。

最好在模型中指定關系。

在帖子模型中,初始化帖子和用戶之間的關系

public $hasOne = 'User';

現在在控制器中使用Contain()獲取鏈接的模型數據

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

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

您將獲得帶有每個帖子記錄的User對象,可用於獲取用戶名,而無需編寫單獨的查詢來獲取用戶名。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM