Search code examples
cakephpormassociationscakephp-3.6

Two users associated to one transaction in CakePHP 3.x


In my app there is a Transaction table with: seller_id, buyer_id and asset_id.

seller_id and buyer_id are id's supposed to point to Users table. To stick to the convention and keep automatic associations both should be called "user_id" (which is of course impossible)

What is the correct way to create such associations in CakePHP 3.x?

My guess is that I should create special association tables: Sellers (id, user_id) Buyers (id, user_id)

and then associations would be trough those tables: Transaction => Sellers, Buyers => Users

Is that correct? Would it work? Is there a better way?


Solution

  • You can define the relationship with different alias and foreign keys like below.

    In your transactions model/Table.

    $this->belongsTo('Sellers' , [ 
        'foreignKey' => 'seller_id',  
        'className' => 'Users'   
    ]); 
    
    $this->belongsTo('Buyers' , [ 
        'foreignKey' => 'buyer_id',  
        'className' => 'Users'   
    ]);  
    

    If you also want to define the relationaship in user model, you can define this in this way.

    In User model/table

    $this->hasMany('BuyerTransactions' , [ 
        'foreignKey' => 'buyer_id',  
        'className' => 'Transactions'   
    ]); 
    
    
    $this->hasMany('SellerTransactions' , [ 
            'foreignKey' => 'seller_id',  
            'className' => 'Transactions'   
        ]);