gpt4 book ai didi

mongodb - Lithium mongodb 模型之间的关系

转载 作者:可可西里 更新时间:2023-11-01 09:11:52 25 4
gpt4 key购买 nike

我在 mongodb 中使用锂,我想知道下面的模型如何从 Posts::find('all'); 获取用户数据查询?

我必须执行两次查询吗?

感谢您的帮助!

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

}
?>

最佳答案

目前关系只存在于关系数据库,如 MySQL 和 SQLite3。因此,您需要进行两次查询才能获得所需的数据。我们现在正在努力为基于文档的数据库添加关系支持,但目前还没有时间表。

您可以对帖子的结果使用 Set::extract 来提取所有用户 ID,然后使用该结果对用户进行单个查询 - 因此您可以从帖子中执行 $userIDs = Set::extract ('/posts/user_id', $posts->data());然后 User::find('all', array('conditions' => array('_id' => $userIDs)));

希望这对您有所帮助。

编辑:您可以在此处找到 set::extract 信息:http://li3.me/docs/lithium/util/Set::extract()

关于mongodb - Lithium mongodb 模型之间的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6286783/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com