CakePHP 3 - 用户所属的ToMany用户

时间:2015-12-28 10:07:55

标签: cakephp orm associations cakephp-3.0

我有一个特定的请求,要在用户之间建立关联。这让我感到困惑,如何减少重复的关联,查询和结果?

起点看起来像这样?

// UsersTable
$this->belongsToMany('Users', [
            'through' => 'Connections',
        ]);

如何在一个查询中获取所有关联,无论用户是否键入" user_from"或" user_to"场?

enter image description here

1 个答案:

答案 0 :(得分:3)

如何使用别名?

您的users表格:

class UsersTable extends Table 
{

    public function initialize(array $config)
    {
        $this->hasMany('ToConnections', [
            'className' => 'Connections',
            'foreignKey' => 'user_to'
        ]);

        $this->hasMany('FromConnections', [
            'className' => 'Connections',
            'foreignKey' => 'user_from'
        ]);

    }
}

和你的connections表:

class ConnectionsTable extends Table 
{

    public function initialize(array $config)
    {
        $this->belongsTo('ToUsers', [
            'className' => 'Users',
            'foreignKey' => 'user_to'
        ]);

        $this->belongsTo('FromUsers', [
            'className' => 'Users',
            'foreignKey' => 'user_from'
        ]);

    }
}

然后,您可以根据需要使用contain()加载关联的模型。

$query = $conections->find()->contain([
    'ToUsers',
    'FromUsers'
]);

$recipients = TableRegistry::get('users');
$query = $recipients->find()->contain([
    'ToConnections.FromUsers',
]);