[英]Access Foreign Tables CakePHP
很抱歉,標題有點令人困惑,我只是不知道如何正確命名。 對於CakePHP項目,我有一個像這樣的表結構。
用戶 ID,名稱,姓氏,用戶記錄
用戶記錄 ID, 用戶 ID, 記錄 ID
記錄 ID,描述
我了解要訪問用戶視圖中的userrecords中間表,我必須執行以下操作
$user['userrecords']['id'];
如何通過用戶視圖整齊地訪問記錄表中的描述 ?
您沒有指定要使用CakePHP 2.x還是3.x,因此我為兩者提供了解決方案。
您所指的關系稱為“有許多人”關系。 由於兩個模型都與鏈接表(userrecords)相關聯,因此您可以根據需要將任意多的記錄自由地關聯到任意數量的用戶。
首先,我考慮將您的“ userrecords”表重命名為“ 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的contains方法從每個模型中自由訪問關聯的記錄:
// 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();
閱讀食譜,它將使您的生活輕松一百萬倍:
因為您的表結構如下:
用戶->用戶記錄->記錄
這樣您只能通過[UserRecord]獲取[Record]
您應該在find命令中設置遞歸屬性。
請在此鏈接上獲取有關遞歸的更多信息: cakephp中遞歸的含義是什么?
我希望這個答案不會誤解您的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.