class Person extends DataObject { public $name; public $contact_id; } class Contact extends DataObject { public $email; } $person = new Person(); $person->name = 'John Doe'; $contact = new Contact(); $contact->email = 'john.doe@example.com'; $person->set_rel('Contact', array( 'local' => 'contact_id', 'foreign' => 'id', 'cardinality' => 'one' )); $person->Contact = $contact; $person->save();
class Book extends DataObject { public $title; } class Author extends DataObject { public $name; } $book = new Book(); $book->title = 'The Catcher in the Rye'; $author1 = new Author(); $author1->name = 'J.D. Salinger'; $author2 = new Author(); $author2->name = 'E.M. Forster'; $book->set_rel('Author', array( 'local' => 'book_id', 'foreign' => 'author_id', 'cardinality' => 'many' )); $book->Author[] = $author1; $book->Author[] = $author2; $book->save();This code creates two database tables, `Book` and `Author`, with a many-to-many relationship between them. The `Book` table has a `title` field, and the `Author` table has a `name` field. The `set_rel()` method is used to define the relationship between the tables. It specifies that each `Book` record can have many `Author` records, identified by the `book_id` foreign key in the `Author` table and the `author_id` foreign key in the `Book` table. The `$book->Author` property is an array of associated `Author` records. In this example, we add two `Author` records to the array and save the `Book` record to the database. Overall, the set_rel() method of the PHP DataObject package library is a powerful tool for defining and manipulating relationships between database tables in PHP. It provides a simple and flexible API for working with a wide range of database systems.