spotorm / spot2

Spot v2.x DataMapper built on top of Doctrine's Database Abstraction Layer

Home Page:http://phpdatamapper.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Relations with conditions, is it possible ?

pasichnyk opened this issue · comments

Is there a way to put some condition into relations()?

If I have a table: "Table 1", with fields: "user_id", "user_type". And I need to connect "user_id" with table "Doctors" or with "Patients" depending on what contains "user_type".

Thank you.

This question isn't Spot related. You can't do that on the relational database level. You can read more about it here.

I had guessed it's impossible on the relational database level. But maybe Spot has a way to walk over it?

I don't think so. You can define dynamic relations, but you shouldn't really. It would be a mess.

I've understood I need to change structure of the tables.
But if I would wanted to make that implementation, do I can get value of the field ?

public static function relations(MapperInterface  $mapper, EntityInterface $entity)
    {
        switch( /* fieldName->value  */ ) //  <- ??
        {
            case "doctor":
                return [
                    "user" => $mapper->belongsTo($entity, "Doctors", "user_id")
                ]
                break;
            case "patient":
                return [
                    "user" => $mapper->belongsTo($entity, "Patients", "user_id")
                ]
                break;
        }
}

In theory you can do that. You must disable foreign key support and have to implement all the things that will ensure database integrity on the application side (and by default is done by the DBMS).

I don't think that's worth it.