Extract data from Relations

落花浮王杯 提交于 2019-12-20 04:07:25

问题


I'm making an online shop. I have two models: Product and Category. Product can have one category, while category can have many products.

I've defined relationships in models. I can access categories and products. But I want to get all products from specific category. I've tried many examples of relational queries with "lazy" and "eager" approach from official documentation, but no success. Can you please explain how to implement it?

Here's my code:

Category controller:

public function relations()
{
    return array(
        'products' => array(self::HAS_MANY, 'Product', 'category_id'),
    );
}

Product controller:

public function relations()
{
    return array(
        'category' => array(self::BELONGS_TO, 'Category', 'category_id'),
    );
}

Thank you.


回答1:


You can do

Category::model()->with('products')->findByPk(1);

you can access fields like

$the_category->products->name

This returns array and you can see content for debugging purposes by

CVarDumper::Dump($the_category->products->name,100,true);

of you can use foreach loop to access each index

$products = $the_category->products;
foreach ($products as $the_product) 
{
    echo "Name: " . $the_product['name'] . "<br />";
}


来源:https://stackoverflow.com/questions/11330040/extract-data-from-relations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!