Extract data from Relations

前端 未结 1 1548
小鲜肉
小鲜肉 2021-01-25 20:24

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

1条回答
  •  北荒
    北荒 (楼主)
    2021-01-25 20:57

    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'] . "
    "; }

    0 讨论(0)
提交回复
热议问题