cakephp表关联查询

来源:互联网 发布:有趣的事情 知乎 编辑:程序博客网 时间:2024/05/21 10:26

users表:

CREATE TABLE `users` (  `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键id',  `name` varchar(30) DEFAULT NULL COMMENT '用户名',  `email` varchar(50) NOT NULL COMMENT '邮箱',  `phone` varchar(50) DEFAULT NULL COMMENT '手机号',  `sex` tinyint(1) DEFAULT '0' COMMENT '性别,0:未知; 1:男; 2:女;',  `age` tinyint(3) DEFAULT '0' COMMENT '年龄',  `created_at` timestamp NOT NULL COMMENT '用户创建时间',  `updated_at` timestamp NOT NULL COMMENT '用户更新时间',  `deleted_at` timestamp NULL DEFAULT NULL COMMENT '用户删除时间',  PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COMMENT='用户表';

articles表:

CREATE TABLE `articles` (  `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键id',  `user_id` int(10) unsigned NOT NULL COMMENT '用户id',  `title` varchar(100) NOT NULL COMMENT '文章标题',  `subtitle` varchar(200) DEFAULT NULL COMMENT '副标题',  `content` text COMMENT '文章内容',  `desc` varchar(500) DEFAULT NULL COMMENT '文章简介',  `created_at` timestamp NOT NULL COMMENT '文章添加时间',  `updated_at` timestamp NOT NULL COMMENT '文章更新时间',  `deleted_at` timestamp NULL DEFAULT NULL COMMENT '删除时间',  PRIMARY KEY (`id`),  KEY `user_index` (`user_id`)) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COMMENT='文章表(article)';

在Model下分别创建UsersTable.phpArticlesTable.php (切记:表的Model创建时一定要加上Table,如users的Model为UsersTable.php,如果是user_info表的Model则为UserInfoTable.php)
UsersTable.php

<?phpnamespace App\Model\Table;use Cake\ORM\Table;class UsersTable extends Table{    public function initialize(array $config)    {        $this->table('users');    }}

ArticlesTable.php

<?phpnamespace App\Model\Table;use Cake\ORM\Table;class ArticlesTable extends Table{    public function initialize(array $config)    {        // $this->setTable('articles');        // Prior to 3.4.0        $this->table('articles');        $this->belongsTo('Users', [            'bindingKey' => 'id',           //Users表的主键id,如果主键字段名为id则可以忽略            'foreignKey' => 'user_id'       //Articles表的外键        ]);    }}

然后在Controller下创建ArticlesController.php,调用关联查询:

$query = $this->Articles->find('all')->contain(['Users'])->where(['Users.id'=>'1'])->toArray();

如果不是在与表名相同的Controller中调用的话要使用:

use Cake\ORM\TableRegistry;$articles = TableRegistry::get('Articles');$query = $articles->find('all')->contain(['Users'])->where(['Users.id'=>'1'])->toArray();

其中,contain表示关联的表,where表示要查询的条件,toArray将结果对象转换为数组格式。

Author:leedaning
本文地址:http://blog.csdn.net/leedaning/article/details/75258649

原创粉丝点击