Marcus Olsson
Marcus Olsson

Reputation: 2527

Find by relation in php-activerecord

I'm trying on php-activerecord for a project – I've used it before in Lithium and CodeIgniter – but I am stuck at something that I think should be pretty easy. But I simply can not wrap my head around it.

So, I've got two tables:

post       |id  |title  |content
           ----------------------
           |1   |Test   |Lorem...

and:

post_meta  |id  |post_id  |publish_date
           ----------------------------
           | 1  |1        |2013-03-23

Now, if I would like to match the title in the post table, and the publish_date in the post_meta-table – how would I go about in the simplest and most elegant way?

As it stands now I seem to have to do two separate queries, first at the meta table to extract the posts with the correct publish_date – and then loop through that one until I find a matching title. Or I can use relationships ($has_one and $belongs_to) – but that way it feels like I am doing it the "other way around" when I want to extract my post-data ($postMetas->post->content).

Feel free to come up with ideas and solutions – or even alternatives to an ORM that makes this is simple and elegant as possible.

Upvotes: 0

Views: 1433

Answers (1)

Nanne
Nanne

Reputation: 64419

You can just use a joined structure in a finder. Check out this part of the manual.

Basically, it says you can join using known connections, and use those as base for what you get returned. The books examples on that page are quite good, see:

# fetch all books joining their corresponding author
 7 $book = Book::all(array('joins' => array('author')));
 8 # sql => SELECT `books`.* FROM `books`
 9 #      INNER JOIN `authors` ON(`books`.author_id = `authors`.id)

Upvotes: 2

Related Questions