Skip to content

Instantly share code, notes, and snippets.

@jbroadway
Created August 21, 2013 16:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jbroadway/6296487 to your computer and use it in GitHub Desktop.
Save jbroadway/6296487 to your computer and use it in GitHub Desktop.
Many-many relations in Elefant.

Import the database via:

./elefant import-db apps/test/conf/install_sqlite.sql

Run on the web via:

http://www.example.com/test/types

You should see the following output:


Doc A

  • Type A
  • Type B

Type B

  • Doc A
  • Doc B
<?php // apps/test/models/Document.php
namespace test;
class Document extends \Model {
public $table = 'test_document';
public $fields = array (
'types' => array (
'many_many' => 'test\Type',
'join_table' => 'test_document_type',
'this_field' => 'document',
'that_field' => 'type'
)
);
}
?>
create table test_document (
id integer primary key,
title char(48) not null,
body text not null
);
insert into test_document values (1, 'Doc A', '...');
insert into test_document values (2, 'Doc B', '...');
create table test_type (
id integer primary key,
name char(48) not null
);
insert into test_type values (1, 'Type A');
insert into test_type values (2, 'Type B');
create table test_document_type (
document int not null,
type int not null,
primary key (document, type)
);
insert into test_document_type values (1, 1);
insert into test_document_type values (1, 2);
insert into test_document_type values (2, 2);
<?php // apps/test/models/Type.php
namespace test;
class Type extends \Model {
public $table = 'test_type';
public $fields = array (
'documents' => array (
'many_many' => 'test\Document',
'join_table' => 'test_document_type',
'this_field' => 'type',
'that_field' => 'document'
)
);
}
?>
<?php // apps/test/handlers/types.php
use test\Document, test\Type;
$doc = new Document (1);
$types = $doc->types ();
printf ("<h3>%s</h3>\n", $doc->title);
foreach ($types as $type) {
printf ("%s<br />\n", $type->name);
}
$type = new Type (2);
$docs = $type->documents ();
printf ("<h3>%s</h3>\n", $type->name);
foreach ($docs as $doc) {
printf ("%s<br />\n", $doc->title);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment