1
votes

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?

1

1 Answers

0
votes

I normally place recursive to -1 and containable in app model, so it applies to all models you create unless you override specifically.

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

Your relationships are fine, although I usually add className and foreignKey just to be safe and clear. In your controller you should do something like this:

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

Recursive will prevent any associated records being included by default, this is good as sometimes you do not need the recursive data and extra data will help slow down your application.

Next adding contain into your find call may seem like a chore but it will be clear and concise what you are querying, any 3rd party developer will understand exactly what you are doing if they know how to use Cake. Hope this helps.