activerecord - Yii ActiveRecord 的 children() 和 parent() 方法是什么?
问题描述
我正在开发使用 Yii 创建的网络商店应用程序,但在文档中找不到任何关于对象的方法children()
和parent()
方法。ActiveRecord
据我了解,它在某种程度上取决于表格中的某些字段,但我找不到任何关系。请你指导我关于这些的事情。
$brands = Category::findOne(['slug' => $slug])->children()->all();
$products = Category::findByRoute(['path' => $path])->parent()->one();
解决方案
假设有三个表,Products、ProductCategory 和 Order。
产品属于单个类别,因此在 Product 模型中定义以下与 BELONGS_TO 的关系。而产品属于多个订单,因此在产品模型中定义与 HAS_MANY 的打击关系。
public function relations() {
return array(
'rel_category' => array(self::BELONGS_TO, 'ProductCategory', 'pro_cat_id'),
'rel_order' => array(self::HAS_MANY, 'Order', 'product_id'),
);
}
现在使用单个命令获取具有类别和订单的产品。
所有产品
$model = Product::model()->findAll();
单一产品
$model = Product::model()->findByPK(1);
您可以使用以下语法访问产品类别
echo $model->rel_category[title];
foreach($model->rel_order as $order):
echo $order->id;
endforeach;
同样的事情可以在 ProductCategory & Order Model 中完成。您只需要在模型中定义正确的关系。
echo "<pre>"; print_r($model); exit(); // this will print whole model for you.
推荐阅读
- c# - 在 c# mono app 中通过 localhost/127.0.0.1 连接到本地 MariaDB MySQL Linux 服务器的 mysql 出现问题
- qt - QML 网格布局问题
- java - 非对称加密字符串,将加密后的字符串和公钥保存到属性文件以供不同程序读取
- python - Python 2.7 - 将自定义对象添加到列表然后打印出属性打印随机值
- c++ - 如何在 GridFS 中设置“contentType”字段?
- python - 为什么程序不打印斐波那契数列?
- javascript - 使用 Angular 5 在 Firebase 中存储数据时无法读取未定义的属性“推送”
- c# - 在.NET(或一般)中创建文档的正确方法是什么?
- java - 带有数组的数学,我可以计算数组内的值吗?
- javascript - 我需要为此功能使用严格的声明吗?它还期待一个“:”而不是一个“。” 对于window.onload?