1

i have a question on mongodb, model cakephp and relationships.

I'd create the following relations:

User -> hasMany -> City
City -> belongsTo -> User

In MongoDB, I have two tables:

users cities (with key user_id)

In cakephp, I have 2 model: User.php

class User extends Model {
public $name = 'User';
public $actsAs = array('Containable');
public $hasMany = array ('City');
..
}

and: City.php

class City extends Model {
public $name = 'City';
public $actsAs = array('Containable');
public $belongsTo = array('User');
.. }

In my controller I use :

$user = $this->User->find('all');

but it doesn't work. In sql dump, cakephp uses a find only on tbl users. Why? Where I wrong?

4

1 回答 1

0

我通常将递归设置为 -1 并且可包含在应用程序模型中,因此它适用于您创建的所有模型,除非您专门覆盖。

class AppModel extends Model {
    public $actsAs = array('Containable');
    public $recursive = -1;
}

你的关系很好,虽然我通常添加 className 和 foreignKey 只是为了安全和清晰。在您的控制器中,您应该执行以下操作:

$users = $this->User->find('all', array(
    'contain' => array(
        'City'
    )
));

默认情况下,递归将阻止包含任何关联的记录,这很好,因为有时您不需要递归数据,而额外的数据将有助于减慢您的应用程序的速度。

接下来将包含添加到您的 find 调用中可能看起来像是一件苦差事,但它会清楚简洁地查询您正在查询的内容,任何第 3 方开发人员如果他们知道如何使用 Cake,就会准确地了解您在做什么。希望这可以帮助。

于 2013-05-08T10:46:43.160 回答