How do I modify a model to return specific db fields?
A Yii question:
The Situation:
I generated a model using Yii's gii code generator tool. The model returns all fields in a given table in a MySQL database.The Problem:
I want to return only fields related to a specific logged-in user based on their user id (which I get fromYii::app()->user->getId()
)
The Question:
How can I modify my model to do this?Code:
(The 'rules' section of my Model class)public function rules()
{
return array(
array('user_id, title, description', 'required'),
array('user_id', 'numerical', 'integerOnly'=>true),
array('description', 'len开发者_如何学Gogth', 'max'=>255),
array('id, user_id, title', 'safe', 'on'=>'search'),
// Is the solution something like this?
//array('user_id', 'compare', 'user_id'=>Yii::app()->user->getId());
);
}
You don't need to modify the model -- how are you doing your search? If you want to use Active Record, you can do something like:
User::model()->find(array('condition'=>'user_id='.Yii::app()->user->getId()));
if the user id is the primary key then:
User::model()->findByPk(Yii::app()->user->getId());
and if you did want to add the condition to your model, you probably want to use a scope to define a search condition, rules are for checking data when it's submitted for insert/update.
For scopes, put this function in your model:
public function scopes() {
return array(
'userid'=>array(
'condition' => 't.user_id = ' . Yii::app()->user->getId(),
),
);
}
then you can use something like this to fetch the data:
User::model()->userid()->find();
(In the above change "User" to the name of your model.)
I would strongly recommend you read the db documentation and work through some tutorials.
精彩评论