spotorm / spot2

Spot v2.x DataMapper built on top of Doctrine's Database Abstraction Layer
http://phpdatamapper.com
BSD 3-Clause "New" or "Revised" License
601 stars 101 forks source link

Check if relation exists with existing model #222

Closed Sysix closed 7 years ago

Sysix commented 7 years ago

Hello Guys,

I'm back with a new question ;)

My Setup:

UserPermRelation (I hope that the Relation is enough Information for my Problem)

 public static function fields()
    {
        return [
            'user_id' => [
                'type' => 'integer',
                'length' => 80,
                'primary' => true,
                'required' => true,
            ],
            'perm_id' => [
                'type' => 'integer',
                'length' => 80,
                'primary' => true,
                'required' => true,
            ]
        ];
    }

    public static function relations(MapperInterface $mapper, EntityInterface $entity)
    {
        return [
            'users' => $mapper->hasMany($entity, '\\AddOn\\Login\\Model\\User', 'id', 'user_id'),
            'perms' => $mapper->hasMany($entity, '\\AddOn\\Login\\Model\\UserPerm', 'id', 'perm_id')
        ];
    }

Now I want to add on my User-Model a Method called $user->hasPerm($perm) How do I solve this? I found example like #186 but it not works like I thought.

Thanks for your help!

nebulousGirl commented 7 years ago

I think you should be able to do it with relation/get method in your model.

public function hasPerm($perm)
{
    $perms = $this->relation('perms'); //returns HasManyRelation object
    if ($perms === false) {
        //Relation is not loaded
    }
    //logic to check if user has perm
    foreach ($perms as $userPerm) {
        //...
    }
    return false; //or whatever
}
Sysix commented 7 years ago

Thanks ;) I thought that could be done easier without an foreach loop.