我在做一个网上商店。我有两个型号:产品和类别。 产品可以有一个类别,而类别可以有很多的产品。
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 />"; }更多推荐
从关系中提取数据
发布评论