cycle / orm

PHP DataMapper, ORM
https://cycle-orm.dev
MIT License
1.23k stars 72 forks source link

💡 Foreign Keys as Primary Key #415

Open gam6itko opened 1 year ago

gam6itko commented 1 year ago

I have an idea!

It would be very useful to use one field instead of two like in Doctrine.

Something like...

class User {
    #[Cycle\Column(type: 'primary')]
    private ?int $id = null;

    #[Cycle\Relation\HasOne(target: UserOneLove::class)]
    private UserOneLove $oneLove;
}

class UserOneLove {
    #[Cycle\PrimaryKey()]
    #[Cycle\Relation\BelongsTo(target: User::class, innerKey: 'user_id')]
    private User $user;
}
gam6itko commented 8 months ago

UPDATED the workaround for this case.

class User {
    #[Cycle\Column(type: 'primary')]
    private ?int $id = null;

    #[Cycle\Relation\HasOne(target: UserOneLove::class, outerKey: 'user_id',  indexCreate: false)]
    private UserOneLove $oneLove;
}

class UserOneLove {
    #[Cycle\Column(type: 'primary', name: 'user_id')]
    private ?int $user_id = null;

    #[Cycle\Relation\BelongsTo(target: User::class, innerKey: 'user_id', indexCreate: false)]
    private User $user;
}
roxblnfk commented 8 months ago

In your examples innerKey and outerKey should contain property name, not column name

rauanmayemir commented 8 months ago

I actually use this sometimes and it works fine. You still do need to declare the field on the child entity as it's a separate column, I don't see a problem with that.

rauanmayemir commented 8 months ago

Also, keep in mind that starting from PHP 8.2 dynamic properties will start giving you a headache, so it's better to have them declared explicitly.