CakePHP 关联的多个表添加读取数据

两个表,一个是users,三个字段id,user_name,user_password,另一个是user_infos,三个字段,id,email,user_id.其中,user_id与表users中的id关联。
我的目标是在往表users插入数据后,取到新记录的id,作为user_infos的user_id字段内容,插入一行到user_infos表.
项目名为cakephp,访问路径为http://localhost/cakephp/,添加用户的URL为http://localhost/cakephp/users/add,查看用户的URL为http://localhost/cakephp/users/
models/user.php:


<?php
class User extends AppModel {
	var $name = 'User';
	var $uses = array (
			'User',
			'UserInfo' 
	);
	//需要用到的模型
	var $hasOne = array (
			"UserInfo" => array (
					'className' => 'UserInfo',
					'conditions' => '',
					'order' => '',
					'dependent' => true,
					'foreignKey' => 'user_id' 
			) 
	);
	//与表user_infos关联
	var $validate = array (
			'user_name' => array (
					'rule' => 'notEmpty',
					'isUnique'=>true
			)
	);
	//验证user_name不为空,且唯一
}
?>

models/user_info.php:


<?php
class UserInfo extends AppModel {
	var $name = 'UserInfo';
	var $validate = array (
			'email' => array (
					'rule' => array (
							'email',
							true 
					) 
			) 
	);
	//<?php
class UserInfo extends AppModel {
	var $name = 'UserInfo';
	var $validate = array (
			'email' => array (
					'rule' => array (
							'email',
							true 
					) 
			) 
	);
	//验证Email格式,好像会联网查域名是否已注册
}
?>
}
?>

controllers/users_controller.php:


<?php
class UsersController extends AppController {
	var $helpers = array (
			'Html',
			'Form' 
	);
	function index() {
		// 读取,访问http://localhost/cakephp/users/时执行
		$allUsers = $this->User->find ( 'all', array (
				'fields' => array (
						'User.id',
						'User.user_name',
						'User.user_password',
						'UserInfo.email' 
				),
				'order' => 'id DESC' 
		) );
		//
		$this->set ( 'allUsers', $allUsers );
	}
	
	function add() {
		// 添加,访问http://localhost/cakephp/users/add时执行
		if (! empty ( $this->data )) {
			// 如果post数据不为空
			if ($this->User->saveAll ( $this->data, array (
					'validate' => 'first' 
			) )) {
				// saveAll方法会同时在两个表添加数据,validate=>first 验证所有模型
				
				$this->flash ( '注册成功', '/users/' );
			} else {
				$this->flash ( '注册失败', '/users/add' );
			}
		
		}
	}
}
?>

下面是View,我把模板扩展名改成了php,这样可以高亮显示
views/add.php:


<p>注册帐号.</p>
<?php echo $form->create('User', array('action' => 'add')) ;?>

<?php
    echo $form->input('User.user_name');
    echo $form->input('User.user_password');
    echo $form->input('UserInfo.email');
?>
<?php echo $form->end('注册');?>

views/index.php:


<table>
<?php 
echo $html->tableHeaders(array_keys(array_merge($allUsers[0]['User'],$allUsers[0]['UserInfo'])));
//生成表头,参数是一个数组,array_merge方法是把两个数组合并
foreach ($allUsers as $thisuser)
{
	echo $html->tableCells(array_merge($thisuser['User'],$thisuser['UserInfo']));
	//生成行,参数是数组
}
?>
</table>

© 2012, 冰冻鱼. 请尊重作者劳动成果,复制转载保留本站链接! 应用开发笔记