使用CakePHP 的Find 方法連接表
要使用CakePHP find 方法從多個表中檢索數據,請考慮以下選項:
標準CakePHP方式
使用actAs 和hasMany 或belongsTo 屬性在模型之間建立關係。例如:
class User extends AppModel { public $actsAs = ['Containable']; public $hasMany = ['Message']; } class Message extends AppModel { public $actsAs = ['Containable']; public $belongsTo = ['User']; }
然後,使用可包含行為:
$this->Message->find('all', [ 'contain' => ['User'], 'conditions' => ['Message.to' => 4], 'order' => 'Message.datetime DESC' ]);
自訂聯接
在尋找方法中定義自訂聯接
$this->Message->find('all', [ 'joins' => [ [ 'table' => 'users', 'alias' => 'UserJoin', 'type' => 'INNER', 'conditions' => ['UserJoin.id = Message.from'] ] ], 'conditions' => ['Message.to' => 4], 'fields' => ['UserJoin.*', 'Message.*'], 'order' => 'Message.datetime DESC' ]);
在尋找方法中定義自訂聯接:
使用兩個相同的關係模型
class User extends AppModel { public $actsAs = ['Containable']; public $hasMany = ['MessagesSent' => ['className' => 'Message', 'foreignKey' => 'from']]; public $belongsTo = ['MessagesReceived' => ['className' => 'Message', 'foreignKey' => 'to']]; } class Message extends AppModel { public $actsAs = ['Containable']; public $belongsTo = ['UserFrom' => ['className' => 'User', 'foreignKey' => 'from']]; public $hasMany = ['UserTo' => ['className' => 'User', 'foreignKey' => 'to']]; }
要基於同一模型的兩個關係檢索數據,請修改模型並使用可包含行為:
$this->Message->find('all', [ 'contain' => ['UserFrom'], 'conditions' => ['Message.to' => 4], 'order' => 'Message.datetime DESC' ]);查找呼叫:
以上是如何使用 Find 方法在 CakePHP 中有效地連接表?的詳細內容。更多資訊請關注PHP中文網其他相關文章!