Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/246.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用mysql访问CakePHP中的相关记录?_Php_Cakephp - Fatal编程技术网

如何使用mysql访问CakePHP中的相关记录?

如何使用mysql访问CakePHP中的相关记录?,php,cakephp,Php,Cakephp,我有一个包含两个表的数据库。一个是博客文章,另一个是用户,由post表中的user_id字段关联。在我的索引页上,我有一个帖子表,我想向其中添加作者,但我想显示用户名而不是他们的ID。我正在尝试向我的帖子对象添加作者字段,如PostsController中的以下内容: public function index() { $this->set('posts', $this->Post->find('all')); foreach ($this as $post){

我有一个包含两个表的数据库。一个是博客文章,另一个是用户,由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非常陌生,因此我认为我对如何使用循环的理解可能不正确。也许有一种更好的方法不需要循环?

默认情况下,CakePHP中的控制器只加载自己的模型。如果您在某个时候需要一个额外的模型,您需要

但这并不能解决您的问题,因为您正在将
find()
操作的结果直接设置到视图中。您需要等待,直到您将用户添加到它。哦,你通常不能用
foreach
遍历
$this
,除非你的类实现了一个类似
迭代器的接口(控制器不应该有理由这样做)


一旦你解决了这个问题。有一种方法可以设置您的
Post
模型,这样它就可以自动用相应的
用户填充
$Post['Post']['author']
,而无需手动操作。

最好在模型中指定关系

在Post模型中,初始化Post和用户之间的关系

public $hasOne = 'User';
现在在控制器中,使用Contain()获取链接模型数据

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

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

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

我没有看到您调用
$this->loadModel('User')
使
$this->User
可用。你是在别的地方做的吗?哦,是的,我现在已经添加了,我现在在foreach中的行上得到了错误“不能将字符串偏移量用作数组”
$posts = $this->Post->find('all')->contain(['User']);

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