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

Relations with conditions, is it possible ? #257

Closed pasichnyk closed 6 years ago

pasichnyk commented 6 years ago

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.

FlipEverything commented 6 years ago

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

pasichnyk commented 6 years ago

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

FlipEverything commented 6 years ago

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

pasichnyk commented 6 years ago

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;
        }
}
FlipEverything commented 6 years ago

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.