0
votes

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?

1

1 Answers

0
votes

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());