Search code examples
phpdatabasenette

How to configure foreign keys in Nette?


I've been reading for a while Nette tutorial for database selects etc, but I still do not understand, how does Nette know, what is foreign key and what is not. Do I need to define it? If so, how? There nothing about it in documentation.

According to this documentation, I do not have to define foreign keys. As I'm used to Java JPA, it sounds a bit strange for me.

Does Nette even generates database? (So far I do not think so).


Solution

  • Nette\Database does not generate database, it inspects the database and discovers the foreign keys – see ActiveRow documentation, in particular the description of M:1 relation:

    Has one relation is a common use-case. Book has one author. Book has one translator. Getting related row is mainly done by ref() method. Ref() method accepts two arguments: target table name and source joining column. See example:

    $book = $context->table('book')->get(1);
    $book->ref('author', 'author_id');
    

    […]

    All of this is fine, but it's somewhat cumbersome, don't you think? Database already contains the foreign keys definitions so why not use them automatically? Let's do that!

    If we call property, which does not exist, ActiveRow tries to resolve the calling property name as “has one” relation. [emphasis mine] Getting this property is the same as calling ref() method with just one argument. We will call the only argument the key. Key will be resolved to particular foreign key relation. The passed key is matched against row columns, and if it matches, foreign key defined on the matched column is used for getting data from related target table.

    You can see how does it work internally in the source code.