【问题标题】:What are the children() and parent() methods of Yii ActiveRecord?Yii ActiveRecord 的 children() 和 parent() 方法是什么?
【发布时间】:2019-08-25 08:29:44
【问题描述】:

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

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

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

【问题讨论】:

  • Yii 中没有children()parent() 这样的东西,这些可能是在这个“web-store-app”中创建的自定义方法。您应该检查该系统的文档(或查看其源代码)。
  • 我怀疑您正在使用Nested Set Model 并且可能正在对模型使用某种扩展,您能否显示Category 模型扩展自哪个类?

标签: activerecord yii yii2 parent children


【解决方案1】:

假设有三个表,Products、ProductCategory 和 Order。

产品属于单个类别,因此在产品模型中定义以下与 BELONGS_TO 的关系。 而Product属于多个订单,所以在product model中用HAS_MANY定义blow关系。

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.

【讨论】:

    猜你喜欢
    • 2011-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-29
    • 2014-09-09
    • 2020-05-30
    • 1970-01-01
    相关资源
    最近更新 更多