Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a Product_faq class which has a $has_many relationship to a Product class. I have a Product class which has a $has_many relationship to the Product_faq class. These two classes are joined using a product_faqs_products table.

I'm trying to get all the Product_faq objects as arrays, including a "product" attribute on each one, which contains an array of the Product objects related to that Product_faq. Here's how I'm doing it now:

$faqs = new Product_faq();
$faqs->where('deleted', 0)->get();

$data['faqs'] = array();

foreach($faqs as $faq){
        $faq_array = $faq->to_array();

        $products = new Product();
        $faq_array['product'] = $products->where_related($faq)->where_join_field($faq, 'deleted', 0)->get()->all_to_array();

        $data['faqs'][] = $faq_array;
}

print_r($data['faqs']);

I feel like there is probably a better way to do this using DataMapper's built-in functionality, but I can't figure it out. Does anyone know a more efficient way to accomplish this?

share|improve this question
add comment

1 Answer

Have you considered setting the attribute auto_populate_has_many on the prodct_faq class? It would auto load all your has many relations on the specific class - convenient but ofcourse a little more resource consuming if you have large data and many relations. Also, the standard name of the relationship-table should be product_product_faq.

This is probably the way i would do it:

class Product_faq extends DataMapper {
    ...
    $auto_populate_has_many = TRUE;
    ...
}

$faqs = (new Product_faq)->where('deleted',0)->get();

print_r($faqs->all_to_array());

If you dont always want to eager load your has many relations you could do like this instead:

$faqs = (new Product_faq)->where('deleted',0)->get();

$faqs->product->get();

print_r($faqs)->all_to_array());
share|improve this answer
    
Thanks jonixj. As far as I can tell, all_to_array() with no fields passed in does not include related models. It only includes the database fields from the parent model. Have you seen otherwise? I believe you're incorrect about the table name. The standard join table name should be a combination of the plural versions of the classes. In my case, the correct one is product_faqs_products. –  flyingL123 May 27 at 2:18
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.