2012-08-18 47 views
1

我想在與用戶,遊戲和遊戲平臺的蛋糕PHP應用程序(前PS3) 創建我的表:CakePHP中找到相關的產品清單其中id是

userGames(遊戲有一個平臺) ID ,名稱,平臺_id

用戶(用戶可以有許多平臺) ID,用戶名

平臺 ID,名稱

users_platforms id,platform_id,user_id

現在我想要選擇所有用戶id = 1的平臺,並列出它的選擇標記。 這裏是SQL查詢:

SELECT platforms.name, platforms.id FROM platforms LEFT JOIN platforms_users ON platforms_users.platform_id=platforms.id WHERE platforms_users.user_id=1 

但我不知道什麼被發現列出此CakePHP中 (「名單」)函數我試圖在用戶控制器類型:

$這個 - >用戶 - > Platform-> find('list',array('conditions',array('User.id'=>'1')));

但是這返回sql問題(undefinded User.id) 任何人都可以幫助我嗎?

回答

3

請儘量將

$this->loadModel('UserPlatform'); 
$this->UserPlatform->bindModel(array(
    'belongsTo' => array('Platform') 
)); 
$this->UserPlatform->find('list', array(
    'fields' => array('Platform.id','Platform.name'), 
    'conditions' => array('UserPlatform.user_id'=>'1'), 
    'recursive' => 1 
)); 
0

必須應用查找功能上連接表

你發現必須與此相同:

$this->PlatformUser->find('list',array('fields'=> 
array('Platform.name','Platform.id'),'conditions'=> array('PlatformUser.id' => 1))); 

你PlatformUser型號必須具備:

public $belongsTo = array(
    'Platform' => array(
     'className' => 'Platform', 
     'foreignKey' => 'platform_id', 
    ), 
    'User' => array(
     'className' => 'User', 
     'foreignKey' => 'user_id', 
    ), 
); 
0

你試圖做的是一個HasAndBelongsToMany關聯。

http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html

hasAndBelongsToMany(HABTM)

我們需要建立一個額外的數據庫中的表來處理HABTM關聯。這個新的連接表名需要包含所涉及的兩個模型的名稱,按字母順序排列,並用下劃線(_)分隔。該表的內容應該是兩個外鍵(它們應該是整數)指向相關模型的主鍵的字段。爲避免任何問題,請勿爲這兩個字段定義組合主鍵。如果你的應用程序需要一個唯一的索引,你可以定義一個。如果您打算向此表中添加任何額外信息,或者使用'with'模型,則應該添加一個額外的主鍵字段(按照慣例'id')。

HABTM需要一個包含兩個型號名稱的單獨連接表。

(這將是UserPlatform表,如果我得到的權利。)

確保表蛋糕和食譜中的主鍵具有按照約定假定的「ID」字段。如果它們與假定的不同,那麼它們必須在模型的主鍵中進行更改。

class Recipe extends AppModel { 
public $hasAndBelongsToMany = array(
    'Ingredient' => 
     array(
      'className' => 'Ingredient', 
      'joinTable' => 'ingredients_recipes', 
      'foreignKey' => 'recipe_id', 
      'associationForeignKey' => 'ingredient_id', 
      'unique' => true, 
      'conditions' => '', 
      'fields' => '', 
      'order' => '', 
      'limit' => '', 
      'offset' => '', 
      'finderQuery' => '', 
      'with' => '' 
     ) 
); 
} 
+1

您可能要添加一些情況下,鏈接的文檔中提供的關鍵數據鏈接到頁面不斷被刪除的。 – talegna 2014-09-09 10:41:23