Bir doktrin kayıtları kullanılan herhangi bir ilişki olup olmadığını test etmek için nasıl

3 Cevap php

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.

Çözelti Ben inanıyorum başlar

$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 

Ne olursa olsun, kullanıcı ve diğer tablolar arasında vardır kaç ilişkilerin çalışacak bir genel çözüm arıyorum.

Teşekkürler!

3 Cevap

$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

Ya da eğer sadece bir Evet / Hayır gerekir:

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

Doktrin yeniyim ama bu deneyin:

$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

Yararlı olacağını umuyoruz!