PHP: OO refactoring - How to model Joins

Let's say I have two models:

class Book
{
    public $book_id;
    public $book_author_id;
    public $title;
}

class Author
{
    public $author_id;
    public $author_name;
}

I'm used to writing something like this:

$DB->query("SELECT book_id, title, author_name 
            FROM book 
            LEFT JOIN author 
                ON book_author_id = author_id
           ");

Suppose I am not interested in the individual queries for this association. How can I continue? Here are some things I've heard:

  • create MySQL VIEW UNION
  • create a VIEW model class

The application I'm working on includes dozens of tables and is highly optimized in procedural code (almost no SELECT * anywhere, for example). I am refactoring to make it more maintainable (I am also the creator), but I would like to have the flexibility of using joins when I need, without compromising the structure of my files and database calls.

Perhaps a related question is related to the inclusion of other models:

class Author
{
    public $author_id;
    public $author_name;

    /* @var Book */ //<--don't really fully understand this but I've seen something like it somewhere
    public (array) $authors_books;
}

, -, .

+5
3

, "", . .

, , . . SQL.

, , .

, . , . - 4 . , GROUP_CONCAT() author_id book_id.

JOIN :

$mapper = $factory->buildMapper('BookCollection');
$collection = $factory->buildCollection('Book');

$collection->setSomeCondition('foobar');
$mapper->fetch( $collection );
foreach ( $collection as $item )
{
    $item->setSomething('marker');
}
$mapper->store( $collection );

P.S. , , . .

P.P.S. , MVC .

+3

- , . , , . getBooks() Author getByAuthor() Book ( , $author->getBooks() Book::getByAuthor($this), Author shouldn ' t Book). (, Book Author, , , $author_books), " ".

+2

, , .

Doctrine framework, ORM PHP.

, .

+1
source

All Articles