0

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?

Zbigniew Ledwoń
  • 682
  • 1
  • 6
  • 19

1 Answers1

2

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'   
    ]);
Rakesh
  • 505
  • 5
  • 12