Yii ActiveRecord的children()和parent()方法是什么?

kupeojn6  于 2022-11-09  发布在  其他
关注(0)|答案(1)|浏览(117)

我正在用Yii创建一个web-store-app,但是在文档中找不到任何关于children()ActiveRecord对象的parent()方法的信息。
据我所知,它在某种程度上取决于某些领域的表格,但我找不到任何关系。你能指导我关于这一点,请。

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

c2e8gylq1#

假设有三个数据表:[产品]、[产品类别]和[订单]。
产品属于单一类别,因此在产品模型中定义与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);

您可以使用以下语法访问Product类别

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.

相关问题