我有一个特定的请求,建立用户之间的关联.这让我感到困惑,如何减少重复的关联,查询和结果?
起点看起来像这样?
// UsersTable $this->belongsToMany('Users',[ 'through' => 'Connections',]);
使用别名怎么样?
您的用户表:
class UsersTable extends Table { public function initialize(array $config) { $this->hasMany('ToConnections',[ 'className' => 'Connections','foreignKey' => 'user_to' ]); $this->hasMany('FromConnections','foreignKey' => 'user_from' ]); } }
和你的连接表:
class ConnectionsTable extends Table { public function initialize(array $config) { $this->belongsTo('ToUsers',[ 'className' => 'Users','foreignKey' => 'user_to' ]); $this->belongsTo('FromUsers','foreignKey' => 'user_from' ]); } }
然后,您可以根据需要使用contains()加载关联的模型.
$query = $conections->find()->contain([ 'ToUsers','FromUsers' ]); $recipients = TableRegistry::get('users'); $query = $recipients->find()->contain([ 'ToConnections.FromUsers',]);