gpt4 book ai didi

php - 我应该直接从 View yii2 调用模型吗

转载 作者:搜寻专家 更新时间:2023-10-31 21:05:03 25 4
gpt4 key购买 nike

我有点困惑,因为,这里是 View 他们直接调用模型,因此不通过 Controller 传递它。 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在底部再次有一个 Best Prictice 部分和主题之一是:( View )不应包含执行数据库查询的代码。这样的代码应该在模型中完成。

谢谢

最佳答案

我同意你对“最佳实践”的理解。我认为我们应该避免调用在 View 中执行数据库查询的方法。另外,所有查询都已在模型中。所以在外面进行外部查询对我来说没有意义。

我使用 Yii2 框架(不是我创建的)参与了一些项目,我只是在这里进行了快速搜索。我遇到过类似情况的唯一情况就是当我们有一个表单或 gridview 并试图显示另一个模型的所有事件时。

在那种情况下,我更愿意在我的模型中创建一个函数来处理这个问题。像这样的东西:

模型

/**
* @return array
*/
public function getAllAnotherModel()
{
return AnotherModel::find()->all();
}

View :

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

关于php - 我应该直接从 View yii2 调用模型吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34004550/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com