我在蛋糕3.2中做了模型关联
在这里,我为同一个表的一个id做了它。
我试图为其他人做这件事,但它根本不起作用
以下是流程。
这个输出我得到了
{
"id": 1,
"publisher_id": 133,
"user_id": 118,
"Publisher": {
"id": 133,
"name": "Sradha sradha"
}
这里我想绑定用户ID,它也属于同一个用户表
输出应该是这样的(我想在下面这样得到)
{
"id": 1,
"publisher_id": 133,
"user_id": 118,
"Publisher": {
"id": 133,
"name": "Sradha sradha"
}
"Users": {
"id": 118,
"name": "Sradha anjo"
}
这里publisher_id和user_id都属于同一个用户表。
$this->AdminRevenues->belongsTo('Users', [
'className' => 'Users',
'foreignKey' => 'user_id',
'propertyName' => 'Users']);
$this->AdminRevenues->belongsTo('Users', [
'className' => 'Publisher',
'foreignKey' => 'publisher_id',
'propertyName' => 'Publisher']);
$totalAdminRevenue = $this->AdminRevenues->find('all')
->contain([
'Users' => ['queryBuilder' => function ($q) {
return $q->select(['id', 'name']);
}]])
->toArray();
请提出建议,任何建议都将受到高度赞赏。
这是做什么的:
$this->AdminRevenues->belongsTo('Users', [
'className' => 'Users',
'foreignKey' => 'user_id',
'propertyName' => 'Users']);
$this->AdminRevenues->belongsTo('Users', [
'className' => 'Publisher',
'foreignKey' => 'publisher_id',
'propertyName' => 'Publisher']);
使用AdminRevenues.user_id
宣布关联,然后立即用关联AdminRevenues.publisher_id
覆盖。实际上第一次打电话给belongsTo
没有做任何事情。
关联别名需要是唯一的,否则诸如$foo = $this->AdminRevenues->Users
之类的代码将是不明确的。因此,只需使关联别名唯一:
$this->AdminRevenues->belongsTo('Users', [
'className' => 'Users',
'foreignKey' => 'user_id',
'propertyName' => 'Users']);
$this->AdminRevenues->belongsTo('Publishers', [ // <---
'className' => 'Users', // <---
'foreignKey' => 'publisher_id',
'propertyName' => 'Publisher']);
它在cakephp 3+中适合我
让我们假设您有两张表,即 1)RequestArticles 3)存储
我们有两个相似的模型: -
1)RequestArticlesTable 2)StoreTable
这是您需要在RequestArticlesTable中定义的关联,我们将两次加入Store表
public function initialize(array $config)
{
parent::initialize($config);
$this->table('request_articles');
$this->displayField('id');
$this->primaryKey('id');
$this->belongsTo( 'yourstore', [
'foreignKey' => 'store_id',
'className' => 'Store'
]);
$this->belongsTo( 'fromstore', [
'foreignKey' => 'from_store_id',
'className' => 'Store'
]);
}
现在我们将在Controller中连接表,如下所示,并设置数据以查看: -
// query to fetch the data from RequestArticles table and set join for store table twice
$requestArticlesDetaile = $this->RequestArticles->get($id, [
'contain' => ['yourstore','fromstore']
]);
// set fetched data to view
$this->set('requestArticlesDetaile', $requestArticlesDetaile);
我的解决方案,在控制器中调用它包含
$this->belongsTo('Senders', [
'foreignKey' => 'sender_id',
'joinType' => 'LEFT',
'className' => 'Manager.Users'
]);
$this->belongsTo('Receivers', [
'foreignKey' => 'receiver_id',
'joinType' => 'LEFT',
'className' => 'Manager.Users'
]);