0

我正在使用一个与其他表有几个可选关系(类型Doctrine_Relation_AssociationDoctrine_Relation_ForeignKey)的学说表。如何测试该表中的记录是否与相关表中的记录有连接。

这是一个让我的问题更清楚的例子。假设您有一个用户,并且一个用户与用户组有多对多关系,并且一个用户可以有一个用户角色我如何测试给定用户是否是任何用户组的一部分或具有角色。

我相信解决方案始于

$relations = Doctrine_Core::getTable('User')->getRelations();
$user = Doctrine_Core::getTable('User')->findOne(1);
foreach($relations as $relation) {
    //here should go a test if the user has a related record for this relation
    if ($relation instanceof Doctrine_Relation_Association) {
       //here the related table probably has more then one foreign key (ex. user_id and group_id)    

    }
    if ($relation instanceof Doctrine_Relation_ForeignKey) {
        //here the related table probably has the primary key of this table (id) as a foreign key (user_id)
    }
}

//true or false
echo $result 

我正在寻找一个通用的解决方案,无论用户和其他表之间有多少关系,它都能正常工作。

谢谢!

4

3 回答 3

0

我是 Doctrine 的新手,但试试这个:

$relations = Doctrine_Core::getTable('User')->getRelations();
$user = Doctrine_Core::getTable('User')->findOne(1);
foreach($relations as $name => $relation) {
    //here should go a test if the user has a related record for this relation
    if($user->relatedExists($name)) {
       echo "this user is associated with some $name";
    }
}
于 2010-05-20T08:51:02.220 回答
0
$user_id = // the user

$q = Doctrine_Query::create()
   ->select('ug.group_id')
   ->from('User u, u.UserGroup ug')
   ->where('u.user_id = ?', $user_id);
$results = $q->execute(array(), Doctrine_Core::HYDRATE_NONE);
foreach($results as $result) $relations[] = $result[0];
$relations = // simple array of group_ids the user belongs to

或者,如果它只是一个是/否,你需要:

$q = Doctrine_Query::create()
   ->select('COUNT(ug.group_id)')
   ->from('User u, u.UserGroup ug')
   ->where('u.user_id = ?', $user_id);
$results = $q->execute(array(), Doctrine_Core::HYDRATE_NONE);
$relation_exists = ($results[0][0]) ? true : false;
于 2010-05-20T12:50:44.807 回答
0

我知道这是一个老问题,但它可能对其他人或什至对您有用。我认为您正在寻找的是relatedExists()您可以在这里找到的方法:http: //docs.doctrine-project.org/projects/doctrine1/en/latest/en/manual/working-with-models.html#clearing-相关记录

希望它会有用!

于 2013-03-30T15:11:24.487 回答