【问题标题】:How to access related record in CakePHP with mysql?如何使用 mysql 访问 CakePHP 中的相关记录?
【发布时间】:2017-06-23 02:04:02
【问题描述】:

我有一个包含两个表的数据库。一个包含博客文章,一个包含用户,由 post 表中的 user_id 字段关联。在我的索引页面上,我有一个帖子表,我想将作者添加到该表中,但是我想显示用户的姓名而不是他们的 ID。我正在尝试在 PostsController 中将作者字段添加到我的帖子对象中:

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 很陌生,所以我认为我对如何使用循环的理解可能不正确。也许有更好的方法不需要循环?

【问题讨论】:

  • 我没有看到您致电 $this->loadModel('User'); 以使 $this->User 可用。你在别的地方做吗?
  • oops 是的,我现在已经添加了,我现在在 foreach 的行中收到错误“不能将字符串偏移量用作数组”

标签: php cakephp


【解决方案1】:

默认情况下,CakePHP 中的控制器只加载它们自己的模型。如果您在某些时候需要额外的模型,您需要load it in manually

但这并不能解决您的问题,因为您正在将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);
}

一旦你解决了这个问题,read up on linking models together。有一种方法可以设置您的 Post 模型,以便它会自动使用相应的 User 填充 $post['Post']['author'],而无需您手动执行此操作。

【讨论】:

    【解决方案2】:

    最好在模型中指定关系。

    在帖子模型中初始化帖子和用户的关系

    public $hasOne = 'User';
    

    现在在控制器中使用 Contain() 来获取链接模型数据

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

    您将获得每个帖子记录的用户对象,您可以使用它来获取用户名,您不需要编写单独的查询来获取用户名。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-23
      • 1970-01-01
      • 1970-01-01
      • 2010-11-10
      • 2010-10-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多