2017-08-31 44 views
1

我剛開始學習cakephp3,所以請原諒我的錯誤。所以我有三個名爲用戶,項目和事件的表,所以關係就像一個用戶可以有多個項目,一個項目可以有很多事件。如何顯示與登錄用戶相關的行

,如果我訪問的基本URL

testap /事件

我想只有那些事件出現在屬於登錄的用戶列表。 注意:事件表只有項目標識不是用戶標識,項目表有用戶標識。

考慮以下方案

Projcts表

ID User_id 
1 1 
2 1 
3 2 
4 3 

事件表

ID Project_id 
1 1 
2 1 
3 1 
4 2 
5 2 
6 3 
7 4 

所以我只想爲他們屬於登錄的用戶(比如用戶顯示事件1to5以身份證1已經登錄)

請告訴我該如何做到這一點?

在此先感謝

+0

這會幫助你https://book.cakephp.org/2.0/en/models/associations-linking-models- together.html –

+0

他說蛋糕3.這可能是一個更好的選擇[檢索數據](https://book.cakephp.org/3.0/en/orm/retrieving-data-and-resultsets.html) – styks

回答

1

新蛋糕3 ORM是太棒了這樣的事情。

// You can replace $this->Users with TableRegistry::get('users') 
// if not in the users controller 
$user = $this->Users->find($this->Auth->user('id'), [ 
    'contain' => [ 
     'Projects.Events' 
    ] 
]); 

你可以得到你這樣的活動

$user->projects[0]->events; 

或者如果你想獲得的事件爲特定用戶,你可以做到這一點向後

$events = $this->Events->find()->matching('Projects.Users', function ($query) use ($userId) { 
    return $query->where(['user_id' => $userId]); 
}); 

我假設你有定義在你的UsersTable初始化函數中

$this->hasMany('Projects'); 

而在你ProjectsTable

$this->hasMany('Events'); 
$this->belongsTo('Users'); 

而在你的事件表

$this->belongsTo('Projects'); 
+0

謝謝這麼多的幫助。它爲我工作:) –