0

在我的应用程序中有一个交易表,其中包含:seller_id、buyer_id 和asset_id。

eller_id 和buyer_id 是id 应该指向Users 表。遵守约定并保持自动关联都应该称为“user_id”(这当然是不可能的)

在 CakePHP 3.x 中创建这种关联的正确方法是什么?

我的猜测是我应该创建特殊的关联表:Sellers (id, user_id) Buyers (id, user_id)

然后关联将通过这些表:交易=>卖家,买家=>用户

那是对的吗?它会起作用吗?有没有更好的办法?

4

1 回答 1

2

您可以使用不同的别名和外键定义关系,如下所示。

在您的事务模型/表中。

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

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

如果你还想在用户模型中定义关系,你可以这样定义。

在用户模型/表中

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


$this->hasMany('SellerTransactions' , [ 
        'foreignKey' => 'seller_id',  
        'className' => 'Transactions'   
    ]);
于 2019-06-25T03:51:27.750 回答