在Lithium中访问多个模型深层关系 [英] Accessing more than one model deep relationships in Lithium
问题描述
在锂的关系中是否可以访问多个模型?
Is it possible to access more than one model deep in a relationship in Lithium?
例如,我有一个用户模型:
For example, I have a User model:
class Users extends \lithium\data\Model {
public $validates = array();
public $belongsTo = array("City");
}
我有一个城市模型:
class Cities extends \lithium\data\Model {
public $validates = array();
public $belongsTo = array("State");
}
和状态模型,等等.
如果我查询的用户与Users::first()
类似,是否可以获取结果中包含的所有关系?我知道我可以做Users::first(array('with' => 'City'))
,但是我也想让每个城市都返回其州模型,所以我可以这样访问它:
If I'm querying for a User, with something similar to Users::first()
, is it possible to get all the relationships included with the results? I know I can do Users::first(array('with' => 'City'))
but I'd like to have each City return its State model, too, so I can access it like this:
$user->city->state->field
现在,我只能让它深入一遍($user->city
),而我不得不再次重新查询,这似乎效率很低.
Right now I can only get it to go one deep ($user->city
) and I'd have to requery again, which seems inefficient.
推荐答案
我猜您正在使用SQL?
I am guessing you are using SQL?
Lithium主要是为noSQL db设计的,因此递归/多联接不是设计目标.
Lithium is mainly designed for noSQL db´s, so recursiveness / multi joins are not a design goal.
- 您可以设置本机sql联接查询并将其转换为模型.
- 使用用户"和州"作为联接查询城市.
- 您可以设置基于数据库的联接视图,并且li3会将其用作单独的模型.
- 您可能应该将计划的递归调用拆分为多个数据库请求.
考虑n个城市对m个州的商. =>先获取城市名,然后再获取州ID和州ID. =>将其作为两个键传递或嵌入状态信息.同样,这对于Users :: all()查询也是可以接受的.
Think about the quotient of n Cities to m States. => fetch the user with city and then the state by the state id. => pass that as two keys or embed the state info. This would be acceptable for Users::all() queries aswell.
使用Lithiums util \ Set类的示例:
Example using Lithiums util\Set Class:
use \lithium\util\Set;
$users = Users::all(..conditions..);
$state_ids = array_flip(array_flip(Set::extract($users->data(), '/city/state_id')));
$stateList = States::find('list',array(
'conditions' => array(
'id' => $state_ids
),
));
这篇关于在Lithium中访问多个模型深层关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!