[英]Same table model association twice in cakephp 3.2
我在蛋糕3.2中完成了模型關聯
在這里,我為同一個表的一個ID完成了此操作。
我已經嘗試過為其他人做,但它根本沒有用
下面是流程。
我得到的輸出
{
"id": 1,
"publisher_id": 133,
"user_id": 118,
"Publisher": {
"id": 133,
"name": "Sradha sradha"
}
在這里我也想綁定用戶ID,該用戶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中定義的關聯
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'
]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.