【发布时间】:2017-11-29 12:26:08
【问题描述】:
有什么方法可以限制 yii 模型中的 n 个内容,我的代码是
public function rules()
{
return [
[['id', 'editedby', 'cat_id', 'prod_id', 'parent', 'order', 'status'], 'integer'],
[['name', 'content', 'excerpt', 'date', 'url', 'posttype'], 'safe'],
];
}
/**
* @inheritdoc
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* @param array $params
*
* @return ActiveDataProvider
*/
public function search($params)
{
$query = Posts::find();
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params,'');
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'id' => $this->id,
'date' => $this->date,
'editedby' => $this->editedby,
'cat_id' => $this->cat_id,
'prod_id' => $this->prod_id,
'parent' => $this->parent,
'order' => $this->order,
'status' => $this->status,
]);
$query->andFilterWhere(['like', 'name', $this->name])
->andFilterWhere(['like', 'content', $this->content])
->andFilterWhere(['like', 'excerpt', $this->excerpt])
->andFilterWhere(['like', 'url', $this->url])
->andFilterWhere(['like', 'posttype', $this->posttype]);
return $dataProvider;
}
如果用户处于免费计划中,这是一个列出产品的模型,必须只显示一个产品,否则必须根据计划计数显示产品会改变我不知道如何添加我需要的条件,例如
if($user_type==1){
$query->andFilterWhere([['id' => SORT_DESC])->one();]);
}
【问题讨论】:
-
你能用
$query->limit(1)吗? -
是的,刚刚找到了这个解决方案,谢谢