CakePHP 3 - Users belongsToMany Users

流过昼夜 提交于 2019-12-18 09:28:16

问题


I have a specific request, to build an association between users. This causes me confusion, how to reduce duplicate associations, query and results?

The starting point would look like this?

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

How to fetch all associations in one query, regardless of whether users key in "user_from" or "user_to" field?


回答1:


How about using aliases?

Your users table:

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'
        ]);

    }
}

And your connections table:

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'
        ]);

    }
}

You can then use contain() to load associated models as required.

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

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


来源:https://stackoverflow.com/questions/34491449/cakephp-3-users-belongstomany-users

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!