Question

When using generateModelsFromDb to generate the models Doctrine makes one to many relations between the relation table and the base tables instead of generating a nm-relation between the base tables themselves. Is there any way to let generateModelsFromDb detect the n-m relation?

Was it helpful?

Solution

You can make your design of the DB, with YAML. If you want to make a N-M relation you need to do something like this (it shows a fool example about dogs with more than one owner and owners with more than a dog)

---
options:
    type: INNODB
    collate: utf8_unicode_ci
    charset: utf8

Human:
    columns:
        id:
            type: integer(4)
            primary: true
            autoincrement: true
        name:
            type: varchar(64)
            notnull: true
        ...
        ...
    relations:
        Dogs:
            foreignAlias: Humans
            class: Dog
            ref_class: Human_Dogs
Dog:
    columns:
        id: 
            type: integer(4)
            autoincrement: true
            primary: true
        owner:
            type: varchar(64)
            notnull: true
        ...
        ...
    relations:
        Humans:
            foreignAlias: Dogs
            class: Human
            ref_class: Human_Dogs
Human_Dogs:
    columns: 
        human_id:
            type: int(4)
            primary: true
        dog_id: 
            type: int(4)
            primary: true
    relations:
        Human:
            foreignAlias: Human_Dogs
        Dog:
            foreignAlias: Human_Dogs

That is going to be the file.yml, so now you can generate the DB from this file. The way you can do that depends a lot on the framework or program you are working with. Anyway here there is a simple way to do it in PHP + Doctrine:

<?php 
$options = array(
      'packagesPrefix'  =>  'Plugin',
      'baseClassName'   =>  'MyDoctrineRecord',
      'suffix'          =>  '.php'
);

Doctrine_Core::generateModelsFromYaml('/path/to/file.yml', '/path/to/model', $options);
?>

With the proper configuration you can autogenerate the id field.

In this link there is a tutorial -> Documentation

I hope this helps you!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top