从关系中提取数据 [英] Extract data from Relations

查看:192
本文介绍了从关系中提取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在做一个网上商店。我有两个型号:产品类别产品可以有一个类别,而类别可以有很多的产品。

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?

下面是我的code:

类别控制器:

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'),
    );
}

感谢你。

推荐答案

您可以做

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

您可以访问诸如领域

$the_category->products->name

这将返回数组,您可以看到调试的内容

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

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

您可以使用的foreach 循环来访问每个首页

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

这篇关于从关系中提取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆