我在cakephp 2申请中有3张桌子:
用户:
个人资料:
论文:
我会证明这一点:
------------------------------------------------------------------
| user->ID | profile -> name | paper -> ID | paper -> title |
------------------------------------------------------------------
| 123 | jack | 12 | test1 |
------------------------------------------------------------------
| 125 | jonn | 15 | mypaper |
------------------------------------------------------------------
etc.
也许用户没有任何纸张
用户有一个配置文件。
用户有很多纸张。
我如何在users_controller中执行此操作?
答案 0 :(得分:1)
您只需要在相应的模型中指定模型关联。将以下文件保存在app / Model文件夹中。
//User Model: User.php
App::uses('AppModel', 'Model');
class User extends AppModel
{
public $name = 'User';
public $useTable = 'users';
public $primaryKey = 'id';
public $hasOne = array('Profile' => array(
'className' => 'Profile',
'foreignKey' => 'user_id'
)
);
public $hasMany = array('Paper' => array(
'className' => 'Paper',
'foreignKey' => 'user_id'
)
);
}
//Profile Model: Profile.php
App::uses('AppModel', 'Model');
class Profile extends AppModel
{
public $name = 'Profile';
public $useTable = 'profiles';
public $primaryKey = 'id';
public $belongsTo = array('User' => array(
'className' => 'User',
'foreignKey' => 'user_id'
)
);
}
//Paper Model: Paper.php
App::uses('AppModel', 'Model');
class Paper extends AppModel
{
public $name = 'Paper';
public $useTable = 'papers';
public $primaryKey = 'id';
public $belongsTo = array('User' => array(
'className' => 'User',
'foreignKey' => 'user_id'
)
);
}
您只需通过一个查询找到用户详细信息及其个人资料详细信息和所有纸质信息:
$result = $this->User->find('all', array('conditions' => array()));
如果您想通过paper的user_id查找用户的个人资料详细信息,那么您应该写下以下内容:
$result = $this->User->Paper('all', array('conditions' => array('Paper.user_id' => $user_id),
'recursive' => '2'));
您可以使用以下方式检查输出:pr($result);die;