我应该直接从视图yii2调用模型吗 [英] Should i calling model direct from view yii2

查看:213
本文介绍了我应该直接从视图yii2调用模型吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有点困惑,因为在这里 他们会直接调用模型,因此不会将其传递给控制器​​. http://www.yiiframework.com/doc-2.0/guide-input -forms.html 滚动到页面底部...

I'm little confused cuz, here in view they do direct call to model thus not passing it through the controller. http://www.yiiframework.com/doc-2.0/guide-input-forms.html Scroll to the bottom of the page...

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 底部又有一个最佳实践"部分,也是主题之一 是:(视图)不应包含执行数据库查询的代码.此类代码应在模型中完成.

And the guide from here http://www.yiiframework.com/doc-2.0/guide-structure-views.html at the bottom again there is a Best Prictice section and one of the topic is: (views) should not contain code that performs DB queries. Such code should be done in models.

谢谢

推荐答案

我同意您对最佳做法"的理解.我认为我们应该避免在视图内部调用执行数据库查询的方法.另外,所有查询都已经在模型中.因此,在外部进行外部查询对我来说没有任何意义.

I agree with you about the understanding of the "Best Practices". I think we should avoid calling methods that perform db queries inside the views. Plus, all queries are already in the model. So does not make sense to me to have external queries outside there.

我使用Yii2框架(不是我创建的)来处理一些项目,我只是在这里进行了快速搜索.我唯一与此类似的情况就是在我们具有表单或网格视图并试图显示所有其他模型的情况下.

I worked with some projects using Yii2 framework (not created by me) and i just made a quick search here. The only case i had of something similar to this, was exactly when we have a form or gridview and tries to show all occurrences of another model.

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

In that scenario I prefer to create a function in my model just to handle this. Something like:

模型

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

查看:

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

这篇关于我应该直接从视图yii2调用模型吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆