我应该直接从视图中调用模型吗?(Yii2)

3

我有些困惑,因为在视图中直接调用模型而不通过控制器传递它。 http://www.yiiframework.com/doc-2.0/guide-input-forms.html 滚动到页面底部...

echo $form->field($model, 'product_category')->dropdownList(
    ProductCategory::find()->select(['category_name', 'id'])->indexBy('id')->column(),
    ['prompt'=>'Select Category']
);

在这里的指南http://www.yiiframework.com/doc-2.0/guide-structure-views.html底部有一个最佳实践部分,其中一个主题是:(视图)不应包含执行DB查询的代码。此类代码应在模型中完成。
谢谢
1个回答

2
我同意您对“最佳实践”的理解。我认为我们应该避免在视图中调用执行数据库查询的方法。此外,所有查询已经在模型中了。因此,在外部进行查询没有意义。
我曾经使用过Yii2框架(不是我创建的),并在这里进行了快速搜索。唯一类似于此的情况是当我们有一个表单或网格视图,并尝试显示另一个模型的所有出现时。
在这种情况下,我更喜欢在我的模型中创建一个函数来处理此事。例如: 模型
/**
 * @return array
 */
public function getAllAnotherModel()
{
    return AnotherModel::find()->all();
}

查看:

<?= $form->field($model, "id_another_model")->dropDownList(
    ArrayHelper::map($model->allAnotherModel, 'id', 'name'),
    ['prompt' => 'Select']
) ?>

更新了答案。我忘记在那个函数中添加前缀“get”,抱歉。你可以选择使用它,或者移除“get”前缀,直接调用$model->allAnotherModel() - Clyff

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接