php - CakePHP - 代码 $hasOne 的结果

标签 php mysql cakephp

我有一个问题,希望不要让你感到困惑。

我想显示文章的用户名(它们是两个表,用户和文章), 相关性是users.id -> posts.author(外键)

这正确显示了我想要的内容:

SELECT `Post`.`id`, `Post`.`author`, `Post`.`title`, `Post`.`content`, `Post`.`description`, `Post`.`status`,
`Post`.`name`, `Post`.`type`, `Post`.`date`, `Post`.`modified`, `Post`.`img`,
`Authors`.`username`, `Authors`.`id`
FROM `myblog`.`posts` AS `Post`
LEFT JOIN `myblog`.`users` AS `Authors` ON (`Authors`.`id` = `Post`.`author`)
WHERE `Post`.`type` = 'post'
ORDER BY `Post`.`date` desc
LIMIT 5

问题在于下面的代码处于 ON

 (`Authors`.`id` = `Post`.`author`)

转换为

 ON (`Authors`.`id` = `Post.author`)

生成“Post”。 `author` 是字符串。

cakePHP中的代码

帖子模型内部

public $hasOne = array(
        'Authors' => array(
            'className' => 'User',
            'foreignKey' =>'id',
            'fields' => array('username','id'),
            'conditions'=>array('Authors.id'=>'Post.author')
        )
    );

postsController 内部

public $paginate = array(
        'Post' => array(
            'paramType' => 'querystring',
            'limit' => 5,
            'conditions'=> array('Post.type'=>'post'),
            'order' => array('Post.date'=>'desc')
            )
        );

...
...
...

public function index() {

        $this->Paginator->settings = $this->paginate;

        $data = $this->Paginator->paginate('Post');

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

返回所有结果,但用户名为空。

不知道吗? 使用子查询?

我尝试转义字符 'conditions' => 数组 ('Authors'.'id' => 'Post.author') 但它不起作用。 ​

最佳答案

我认为问题出在关系类型上。帖子属于一个用户,但一个用户可以拥有多个帖子。所以,关系应该是-

User.php

public $hasMany = array('Post');

Post.php

public $belongsTo = array('User');

关于php - CakePHP - 代码 $hasOne 的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22908549/

相关文章:

php - 使用 shell 样式的通配符(例如,*)匹配字符串

php - 为什么 num_rows 给出表中所有行的数量?

javascript - 当前 Ajax 请求的最佳实践

PHP/MySQL - 如果变量不存在则更新数组

php - 如何使用一对多、双向 Doctrine ?

mysql - 未使用 MySql 数据库中的 where 获取(SELECT)所有结果

php - CSV 导出,包括其他表中的行

php - Cakephp 和 iOS 10.3.2

php - php mysql中group_concat的错误格式

PHP 对 REST API 的多个 cURL 请求停止