开发者

How to test if a doctrine records has any relations that are used

I'm using a doctrine table that has several optional relations (of types Doctrine_Relation_Association and Doctrine_Relation_ForeignKey) with other tables. How can I test if a record from that table has connections with records from the related table.

Here is an example to make my question more clear. Assume that you have a User and a user has a many to many relation with Usergroups and a User can have one Userrole How can I test if a give user is part of any Usergroups or has a role.

The solution starts I believe with

$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 

I'm looking for a general solution that will work no matter how many relations there are between user and other tables.

Thanks!


$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

Or if it's just a Yes/No you need:

$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;


I'm new to Doctrine but try this:

$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";
    }
}


I know this is an old question, but it could be useful to someone else or maybe even to you. I think what you were looking for was the relatedExists() method that you can find here: http://docs.doctrine-project.org/projects/doctrine1/en/latest/en/manual/working-with-models.html#clearing-related-records

Hope it will be useful!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜