CakePHP查找id为的关联项列表

时间:2012-08-18 14:01:04

标签: php list cakephp find associations

我想用用户,游戏和游戏平台创建蛋糕php应用程序(适用于前PS3) 我得到了桌子:

userGames(游戏有一个平台) id,name,platform_id

用户(用户可以拥有多个平台) id,用户名

平台 id,name

users_platforms id,platform_id,user_id

现在我想选择所有用户id = 1平台,并将其列为select标签。 这是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中通过find('list')函数列出这个 我尝试输入用户控制器:

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

但是这会返回sql问题(未完成的User.id) 有人可以帮帮我吗?

3 个答案:

答案 0 :(得分: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
));

答案 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',
    ),
);

答案 2 :(得分:0)

您要做的实际上是HasAndBelongsToMany协会。

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

  

hasAndBelongsToMany(HABTM)

     

我们需要在数据库中设置一个额外的表来处理HABTM关联。这个新的连接表的名称需要包括所涉及的两个模型的名称,按字母顺序排列,并用下划线(_)分隔。表的内容应该是两个字段,它们是指向所涉及模型的主键的外键(应该是整数)。要避免任何问题,请不要为这两个字段定义组合主键。如果您的应用程序需要唯一索引,则可以定义一个索引。如果您计划向此表添加任何额外信息,或使用“with”模型,则应添加其他主键字段(按照惯例'id')。

     

HABTM需要一个包含两个模型名称的单独连接表。

(如果我做对了,这将是UserPlatform表。)

  

确保表格蛋糕和食谱中的主键具有常规假设的“id”字段。如果它们与假设不同,则必须在模型的primaryKey中更改它们。

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' => ''
        )
);
}
相关问题