Rocky
Rocky

Reputation: 91

How to retrieve data from many to many relationship tables with Doctrine

Let say I have 3 tables: Book, Author and BookAuthor.

  • Book has id, name
  • Author has id, name
  • BookAuthor has id, book_id, author_id

I want to find all books of an author, and I know author_id. Can anyone show me how to do this with Doctrine Query Language?

Upvotes: 0

Views: 1678

Answers (1)

denys281
denys281

Reputation: 2014

I think there are few ways:

1

In action:

 $this->books= Doctrine::getTable('BookAuthor')->getBookAuthor($author_id);

In model:

  public function getBookAuthor($author_id)
        {
            $q = $this->createQuery('a')
                       ->Where('a.author_id=?',$author_id)
                       ->addORDERBY ('created_at DESC');

        return $q->execute();
        }

2

Sometime for example you have some parameter in book table, for example book can be active or not.

In action:

 $this->books= Doctrine::getTable('Book')->getBookAuthor($author_id);

In model:

 public function getBookAuthor($author_id)
        {
            $q = $this->createQuery('a')
                       ->andWhere('a.active=1')
                       ->leftJoin('a.BookAuthor o')
                       ->andWhere('o.author_id=?',$author_id)
                       ->addORDERBY ('created_at DESC');


    return $q->execute();
    }

Upvotes: 3

Related Questions