首页 > 解决方案 > Yii ActiveRecord 的 children() 和 parent() 方法是什么?

问题描述

我正在开发使用 Yii 创建的网络商店应用程序,但在文档中找不到任何关于对象的方法children()parent()方法。ActiveRecord

据我了解,它在某种程度上取决于表格中的某些字段,但我找不到任何关系。请你指导我关于这些的事情。

$brands = Category::findOne(['slug' => $slug])->children()->all();
$products = Category::findByRoute(['path' => $path])->parent()->one();

标签: activerecordyiiyii2parentchildren

解决方案


假设有三个表,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.

推荐阅读