从关系中提取数据

编程入门 行业动态 更新时间:2024-10-28 15:31:53
本文介绍了从关系中提取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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 />"; }

更多推荐

从关系中提取数据

本文发布于:2023-10-29 22:52:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1541000.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:关系   数据

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!