PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, February 21, 2022

[FIXED] CakePHP 3 - Users belongsToMany Users

 February 21, 2022     associations, cakephp, cakephp-3.0, orm     No comments   

Issue

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?

enter image description here


Solution

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


Answered By - Inigo Flores
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing