Rumah > Artikel > pembangunan bahagian belakang > Bagaimana untuk Mendapatkan Data daripada Berbilang Jadual Menggunakan Kaedah Cari CakePHP dengan JOIN?
To execute the specified SQL query using CakePHP's find method, you can employ two approaches:
<code class="php">class User extends AppModel { public $actsAs = array('Containable'); public $hasMany = array('Message'); } class Message extends AppModel { public $actsAs = array('Containable'); public $belongsTo = array('User'); }</code>
<code class="php">$this->Message->find('all', array( 'contain' => array('User') 'conditions' => array( 'Message.to' => 4 ), 'order' => 'Message.datetime DESC' ));</code>
<code class="php">$this->Message->find('all', array( 'joins' => array( array( 'table' => 'users', 'alias' => 'UserJoin', 'type' => 'INNER', 'conditions' => array( 'UserJoin.id = Message.from' ) ) ), 'conditions' => array( 'Message.to' => 4 ), 'fields' => array('UserJoin.*', 'Message.*'), 'order' => 'Message.datetime DESC' ));</code>
You can establish two relationships to the same model:
<code class="php">class User extends AppModel { public $actsAs = array('Containable'); public $hasMany = array( 'MessagesSent' => array( 'className' => 'Message', 'foreignKey' => 'from' ) ); public $belongsTo = array( 'MessagesReceived' => array( 'className' => 'Message', 'foreignKey' => 'to' ) ); } class Message extends AppModel { public $actsAs = array('Containable'); public $belongsTo = array( 'UserFrom' => array( 'className' => 'User', 'foreignKey' => 'from' ) ); public $hasMany = array( 'UserTo' => array( 'className' => 'User', 'foreignKey' => 'to' ) ); }</code>
Example query:
<code class="php">$this->Message->find('all', array( 'contain' => array('UserFrom') 'conditions' => array( 'Message.to' => 4 ), 'order' => 'Message.datetime DESC' ));</code>
Atas ialah kandungan terperinci Bagaimana untuk Mendapatkan Data daripada Berbilang Jadual Menggunakan Kaedah Cari CakePHP dengan JOIN?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!