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
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.
Yep,
Since you are using active record relations, all you would have to do
$station = Station::model()->findAll();
$station->store
and now you have access to the store object in the database, so you can do
$station->store->id
$station->store->name
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.
精彩评论