在Lithium中,是否有可能访问深入关系中的多个模型?
例如,我有一个用户模型:
class Users extends \lithium\data\Model {
public $validates = array();
public $belongsTo = array("City");
}我有一个City模型:
class Cities extends \lithium\data\Model {
public $validates = array();
public $belongsTo = array("State");
}和State模型,等等。
如果我查询一个类似于Users::first()的用户,是否有可能获得包含在结果中的所有关系?我知道我可以做Users::first(array('with' => 'City')),但是我想让每个城市也返回它的州模型,这样我就可以像这样访问它:
$user->city->state->field现在我只能让它深入一层($user->city),然后我必须再次查询,这似乎效率很低。
发布于 2012-03-23 21:18:05
我猜你用的是SQL?
锂主要是为noSQL数据库设计的,因此递归/多连接不是设计目标。
想一想n个城市对m个州的商。=>先获取用户的城市,然后根据州id获取州。=>将其作为两个密钥传递或嵌入状态信息。这对于Users::all()查询也是可以接受的。
使用Lithium 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
),
));发布于 2013-02-21 00:05:31
使用最近的母版,您可以使用以下嵌套表示法:
Users::all( array(
'with' => array(
'Cities.States'
)
)); 它将为您执行连接。
发布于 2012-06-09 23:33:29
您可以用这种方式设置关系,但您必须使用更详细的关系定义。请看一下在构造Relationship时传递的数据,了解有关您可以使用的选项的详细信息。
class Users extends \lithium\data\Model {
public $belongsTo = array(
"Cities" => array(
"to" => "app\models\Cities",
"key" => "city_id",
),
"States" => array(
"from" => "app\models\Cities",
"to" => "app\models\States",
"key" => array(
"state_id" => "id", // field in "from" model => field in "to" model
),
),
);
}
class Cities extends \lithium\data\Model {
public $belongsTo = array(
"States" => array(
"to" => "app\models\States",
"key" => "state_id",
),
);
}
class States extends \lithium\data\Model {
protected $_meta = array(
'key' => 'id', // notice that this matches the value
// in the key in the Users.States relationship
);
}在用户上使用州关系时,请确保始终在同一查询中包括城市关系。例如:
Users::all( array(
'with' => array(
'Cities',
'States'
)
) ); 我从来没有尝试过使用belongsTo关系,但我使用hasMany关系以同样的方式进行了工作。
https://stackoverflow.com/questions/9836392
复制相似问题