Danny
Danny

Reputation: 4754

Symfony models with foreign keys

So I have 2 models. Users and Groups. Each group has a user as the creator and a group has many users. The FK of these tables are set up correctly, but I was wondering if there was an easier way to get all related FK objects from other objects. For example, with a group object, is there a built in method to get the user object of the creator? Or for a user, is there a built in method to get all group object that he belongs to? I couldn't find out how to do this with the documentation on the symfony page. From what I see I feel like I need to create methods and use doctrine to access the appropriate tables using the current objects id and so on.

Thanks!

Some sample schema:

Group:
  actAs: { Timestampable: ~ }
  columns:
    name: { type: string(500), notnull: true }
    image: { type: string(255) }
    type: { type: string(255), notnull: true }
    created_by_id: { type: integer }
  relations: 
    User: { onDelete: SET NULL, class: User, local: created_by_id, foreign: id, foreignAlias: groups_created }

Upvotes: 0

Views: 807

Answers (1)

Amy B
Amy B

Reputation: 17977

You need to show us your code for a decent answer, but it will be something like below.

YAML:

Group:
    columns:
        ..........
        creator_id:     { type: integer(4), notnull: true }
    relations:
        Creator:        { class: User, local: creator_id, foreign: id }

PHP:

$user = $group->getCreator();

Upvotes: 4

Related Questions