两个用户与 CakePHP 中的一个事务相关联 3.x
Two users associated to one transaction in CakePHP 3.x
在我的应用程序中有一个交易 table 包含:
seller_id、buyer_id 和 asset_id。
seller_id 和 buyer_id 是应该指向用户 table 的 ID。为了遵守约定并保持自动关联,两者都应称为 "user_id"(这当然是不可能的)
在 CakePHP 中创建此类关联的正确方法是什么 3.x?
我的猜测是我应该创建特殊关联 tables:
卖家 (id, user_id)
买家 (id, user_id)
然后关联将通过那些 tables:
交易 => 卖家、买家 => 用户
对吗?行得通吗?有没有更好的方法?
您可以定义不同别名和外键的关系,如下所示。
在您的交易中model/Table。
$this->belongsTo('Sellers' , [
'foreignKey' => 'seller_id',
'className' => 'Users'
]);
$this->belongsTo('Buyers' , [
'foreignKey' => 'buyer_id',
'className' => 'Users'
]);
如果你也想在用户模型中定义关系,你可以这样定义。
在用户中 model/table
$this->hasMany('BuyerTransactions' , [
'foreignKey' => 'buyer_id',
'className' => 'Transactions'
]);
$this->hasMany('SellerTransactions' , [
'foreignKey' => 'seller_id',
'className' => 'Transactions'
]);
在我的应用程序中有一个交易 table 包含: seller_id、buyer_id 和 asset_id。
seller_id 和 buyer_id 是应该指向用户 table 的 ID。为了遵守约定并保持自动关联,两者都应称为 "user_id"(这当然是不可能的)
在 CakePHP 中创建此类关联的正确方法是什么 3.x?
我的猜测是我应该创建特殊关联 tables: 卖家 (id, user_id) 买家 (id, user_id)
然后关联将通过那些 tables: 交易 => 卖家、买家 => 用户
对吗?行得通吗?有没有更好的方法?
您可以定义不同别名和外键的关系,如下所示。
在您的交易中model/Table。
$this->belongsTo('Sellers' , [
'foreignKey' => 'seller_id',
'className' => 'Users'
]);
$this->belongsTo('Buyers' , [
'foreignKey' => 'buyer_id',
'className' => 'Users'
]);
如果你也想在用户模型中定义关系,你可以这样定义。
在用户中 model/table
$this->hasMany('BuyerTransactions' , [
'foreignKey' => 'buyer_id',
'className' => 'Transactions'
]);
$this->hasMany('SellerTransactions' , [
'foreignKey' => 'seller_id',
'className' => 'Transactions'
]);