CakePHP の Find メソッドを使用したテーブルの結合
CakePHP の find メソッドを使用して複数のテーブルからデータを取得するには、次のオプションを検討してください。
スタンダードケーキPHP方法
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' ]);
2 つの関係を使用して、同じモデル
同じモデルへの 2 つの関係に基づいてデータを取得するには、モデルを変更し、包含可能な動作を使用します:
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 中国語 Web サイトの他の関連記事を参照してください。