Search code examples
mongodbphp-mongodblithium

Lithium mongodb relation between models


I'm using lithium with mongodb and I would like to know with my models below how I could get the data of the user from Posts::find('all'); query?

Do I have to do two queries?

Thanks for your help!

    <?php
    namespace app\models;

    class Posts extends \lithium\data\Model {

        protected $_schema = array(
            '_id'           =>  array('type' => 'id'),
            'name'          =>  array('type' => 'string', 'null' => false),
            'description'   =>  array('type' => 'string', 'null' => false),
            'created'       =>  array('type' => 'datetime'),
            'updated'       =>  array('type' => 'datetime'),
            'user_id'       =>  array('type' => 'integer')
        );

        protected $_meta = array(
            'key' => '_id',
        );

        public $belongsTo = array('Users');


    }
    ?>


<?php
namespace app\models;

class Users extends \lithium\data\Model {

    public $hasMany = array('Posts');

    public $validates = array(
        'name' => 'Please enter a name',
    );

    protected $_schema = array(
        '_id'       =>  array('type' => 'id'),
        'name'      =>  array('type' => 'string', 'null' => false),
        'slug'      =>  array('type' => 'string', 'null' => false),
        'created'   =>  array('type' => 'datetime', 'null' => false),
    );

}
?>

Solution

  • Currently relationships only exist for relational databases like MySQL and SQLite3. As such you'll need to make two queries to get the data you want. We're working on adding support for relationships for document based databases now however there currently is no timeframe on that.

    You can use Set::extract on your result from posts to pull all of the user id's out then use the results from that to make a single query from users - so from posts you could do $userIDs = Set::extract('/posts/user_id', $posts->data()); then User::find('all', array('conditions' => array('_id' => $userIDs)));

    hope this helps.

    edit: You can find set::extract information here: http://li3.me/docs/lithium/util/Set::extract()