Should i calling model direct from view yii2

偶尔善良 提交于 2019-12-10 18:49:19

问题


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']
);

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.

Thanks


回答1:


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.

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:

MODEL

/**
 * @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']
) ?>


来源:https://stackoverflow.com/questions/34004550/should-i-calling-model-direct-from-view-yii2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!