2011-06-09 137 views
4

我使用锂与mongodb,我想知道我的模型如何可以从Posts :: find('all')获取用户的数据。查询?锂的mongodb模型之间的关系

我必须做两个查询吗?

感谢您的帮助!

<?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), 
    ); 

} 
?> 

回答

4

当前关系只存在于像MySQL和SQLite3这样的关系型数据库中。因此,您需要进行两个查询才能获取所需的数据。我们正在努力增加对基于文档的数据库关系的支持,但目前没有时间表。

您可以使用Set :: extract对帖子中的结果进行抽取,以便将所有用户标识的出来,然后使用该结果从用户进行单个查询 - 因此,您可以执行的操作$ userIDs = Set :: extract('/ posts/user_id',$ posts-> data());那么User :: find('all',array('conditions'=> array('_ id'=> $ userIDs)));

希望这有助于。

编辑:您可以在这里找到设置::提取信息:http://li3.me/docs/lithium/util/Set::extract()

+0

Wahouh我喜欢Set :: extract! – 2011-06-10 22:26:23

1

我必须做两个查询?

这将取决于您的模式。

案例#1

如果UsersPosts是两个不同的集合,那么你将需要两个不同的查询。

案例#2

如果Users是顶级对象,并Posts“属于” Users,那么你会做一些等同于db.users.find({ posts : {$exists:true} })

我不是100%清楚锂的处理方式。我无法找到一个简单的例子,说明锂是否正在做#1或#2。

+0

嘿盖茨!感谢您的回答!我也是,我找不到任何“属于”的例子,我试过但我不知道如何使用它。我实际上在做案例#1。如果我找到解决方案,我会保持更新。 – 2011-06-10 04:12:01

1

正如Howard3说,目前MongoDB的没有关系的支持,因此“属于”将不能工作。

实际的决定取决于您的应用程序,但我认为它将成为某种形式的博客(用户和帖子)。根据MongoDB模式设计的最佳实践,我将它们放在不同的集合中,因为它们是“一级集合”。更适合嵌入式文档将是帖子和评论。

另外,当你在最新的主人身上时,你不必定义'关键'的东西。您现在可以编写一个custom find method,当关系支持在内核中完成时,可以轻松地将其更换为更通用的解决方案。

如果您需要更多交互式帮助,请访问freenode上的#li3。