【问题标题】:how to limit content in yii model如何在 yii 模型中限制内容
【发布时间】: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)吗?
  • 是的,刚刚找到了这个解决方案,谢谢

标签: php yii


【解决方案1】:

正如 Raul Sauco 已经提到的,你可以使用类似的东西

$query->andFilterWhere([['id' => SORT_DESC])->limit($user_type == 1 ? 1 : 20);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-12
    • 2016-12-29
    • 2015-07-01
    • 2020-04-14
    • 2011-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多