orm icon indicating copy to clipboard operation
orm copied to clipboard

💡 Foreign Keys as Primary Key

Open gam6itko opened this issue 2 years ago • 4 comments

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 avatar Jun 15 '23 12:06 gam6itko

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

gam6itko avatar Mar 01 '24 15:03 gam6itko

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

roxblnfk avatar Mar 04 '24 08:03 roxblnfk

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 avatar Mar 05 '24 06:03 rauanmayemir

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.

rauanmayemir avatar Mar 05 '24 06:03 rauanmayemir