相关活动记录 - 控制器或模型方法?
我正在尝试从视图访问 Yii 中的相关模型信息,并且需要创建一个方法。我不确定该方法是否应该放入控制器或模型中......
场景是: - 车站“有一个”商店 - 商店“属于”车站(“商店”表有“station_id”列)
在车站的详细视图(车站/视图/1)中,我想检查这个特定车站是否有商店,如果所以,我想从那家商店归还ID。
所以我的问题是:
1)我是否创建一个方法来查找此信息并将其放入控制器或模型中?
2) 我应该向车站还是商店询问此信息?
3)我知道控制器是模型和视图之间的粘合剂,所以我把这个方法放在控制器中是有意义的。然而,在 Yii 中,在视图文件中包含以下内容似乎是常见的做法:
CHtml::listData(Company::model()->findAll()
在我看来,视图直接与模型交互
I'm trying to access related model info in Yii from a view and need to create a method. Im not sure if the method should go in the controller or the model...
The scenario is:
- A Station 'Has One' Store
- A Store 'Belongs To' Station (the 'store' table has a 'station_id' column)
In the detail view for a Station (station/view/1), I want to check weather this particular Station has a Store, and if so, I want to return the ID from that store.
So my questions are:
1) Do i create a method to find this info and put it in the Controller or Model?
2) Should I be asking the Station for this info, or the Store?
3) I know that the Controller is the glue between models and views, so it make sense to me to put this method in the controller. However, in Yii it seems common practice to have the following in a view file:
CHtml::listData(Company::model()->findAll()
Which seems to me like the view is interacting directly with a model
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在模型中,如果您使用 Active Record,则可以在关系功能中设置 Station 和 Store 模型之间的关系。然后可以使用一小行代码获取商店的 id(例如 $storeId = $model->store->id;)。因此,您可以轻松地将这段代码放入控制器中,并且仍然保持控制器精简(精简控制器,胖模型)。
您应该向车站“询问”商店,因为您已经知道车站的 ID。
如果视图和模型之间不需要额外的逻辑,您可以跳过控制器。但不要忘记诸如授权之类的事情。
In the models you can set up the relation between the Station and the Store models in the relations function if you use Active Record. Obtaining the id of a Store is then possible using one short line of code (something like $storeId = $model->store->id;). So you can easily put this code into your controller and still keep the controller lean (Lean controllers, fat models).
You should 'ask' the Station for the Store because you already know the id of the Station.
You can skip the controller if no extra logic between the view and the model is required. But don't forget things like authorization.
是的,
由于您正在使用活动记录关系,所以您所要做的
就是现在您可以访问数据库中的存储对象,因此您可以执行
等等操作。
是的,Yii 很棒:)但这只是 ActiveRecord :)
另外常见的做法是与控制器通信,而不是直接从视图与模型通信。控制器处理验证并在验证正确后将其传递给模型。
Yep,
Since you are using active record relations, all you would have to do
and now you have access to the store object in the database, so you can do
and etc.
Yes Yii is amazing :) but that is just ActiveRecord :)
Also its common practice to communicate with the controller and not the model directly from the view. Controller handles validations and passes it to the model once they are correct.