如果标题有点令人困惑,我很抱歉,我只是不知道如何正确调用它。我的CakePHP项目有一个像这样的表结构。
用户 ID,姓名,用户记录
userrecords id,user_id,records_id
记录 ID,说明
我了解要访问用户视图中的用户记录中间表,我必须执行类似
的操作$user['userrecords']['id'];
如何通过用户视图巧妙地访问记录表中的说明?
答案 0 :(得分:2)
您没有说明您是否正在使用CakePHP 2.x或3.x,因此我为两者提供了解决方案。
您所指的关系称为"拥有并属于许多" 关系。由于您的两个模型都与链接表(用户记录)相关联,因此您可以根据需要自由地将尽可能多的记录关联。
首先,我会考虑重命名您的用户记录'表到' users_records'与CakePHP很好地配合。
首先,在您的用户模型中定义您的关系:
// Using CakePHP 2.x:
class User extends AppModel {
public $actsAs = array('Containable'); // Instantiate Containable behavior
public $hasAndBelongsToMany = array(
'Record' =>
array(
'className' => 'Record',
'joinTable' => 'users_records',
'foreignKey' => 'user_id',
'associationForeignKey' => 'record_id'
)
);
}
// Using CakePHP 3.x:
class UsersTable extends Table
{
public function initialize (array $config)
{
$this->belongsToMany('Records', [
'joinTable' => 'users_records' // Defines our linking table
]);
}
}
现在,我们必须在记录模型中定义我们的关系:
// Using CakePHP 2.x:
class Record extends AppModel {
public $actsAs = array('Containable'); // Instantiate Containable behavior
public $hasAndBelongsToMany = array(
'User' =>
array(
'className' => 'User',
'joinTable' => 'users_records',
'foreignKey' => 'record_id',
'associationForeignKey' => 'user_id'
)
);
}
// Using CakePHP 3.x:
class RecordsTable extends Table
{
public function initialize (array $config)
{
$this->belongsToMany('Users', [
'joinTable' => 'users_records' // Defines our linking table
]);
}
}
现在,我们可以使用ORM的包含方法从每个模型中自由访问相关记录:
// Using CakePHP 2.x:
// Getting 'User' and associated 'Record' models in Controller:
$this->loadModel('User');
$this->User->find('all', array('contain' => 'Record'));
// Getting 'Record' and associated 'User' models in Controller:
$this->loadModel('Record');
$this->Record->find('all', array('contain' => 'User'));
// Using CakePHP 3.x:
// Getting 'User' and associated 'Record' models:
$users_table = TableRegistry::get('Users');
$users = $users_table->find()->contain('Records')->all();
// Getting 'Record' and associated 'User' models:
$records_table = TableRegistry::get('Records');
$records = $records_table->find()->contain('Users')->all();
阅读食谱,它将使您的生活更轻松一百万次:
CakePHP 2.x Containable Behavior
CakePHP 2.x Has And Belongs To Many Relationship
CakePHP 3.x belongsToMany Relationship
答案 1 :(得分:1)
答案 2 :(得分:0)
因为你的表结构如下:
用户 - > UserRecord - >记录
这样你才能通过[UserRecord]
获得[Record]您应该在find命令中设置递归属性。
请参阅此链接了解有关递归的更多信息:what is the meaning of recursive in cakephp?
我希望这个答案不会误解你的问题。