简体   繁体   English

数组中与CodeIgniter DataMapper相关的对象

[英]CodeIgniter DataMapper related objects in array

I have a Product_faq class which has a $has_many relationship to a Product class. 我有一个Product_faq类,它与Product类具有$ has_many关系。 I have a Product class which has a $has_many relationship to the Product_faq class. 我有一个Product类,它与Product_faq类具有$ has_many关系。 These two classes are joined using a product_faqs_products table. 使用product_faqs_products表将这两个类连接在一起。

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. 我试图将所有Product_faq对象作为数组获取,每个对象都包含一个“ product”属性,其中包含与该Product_faq相关的Product对象的数组。 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. 我觉得使用DataMapper的内置功能可能有更好的方法,但是我无法弄清楚。 Does anyone know a more efficient way to accomplish this? 有谁知道实现这一目标的更有效方法?

Have you considered setting the attribute auto_populate_has_many on the prodct_faq class? 您是否考虑过在prodct_faq类上设置属性auto_populate_has_many? 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. 另外,关系表的标准名称应为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());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM