在Yii2中为相关模型设置属性安全

时间:2017-08-09 18:24:21

标签: yii2

我需要将属性设置为相关模型的安全性。我使用具有翻译关系的搜索模型。在那里,我想将title属性设置为安全。

问题是相关的ArticleTranslation模型中需要title属性。

我使用creocoder的yii2可翻译行为。

class ArticleSearch extends Article
{
    public function rules()
    {
        return [
            [['id', 'user_id', 'status', 'category_id', 'created_at', 'updated_at'], 'integer'],
            [['title', 'summary', 'content'], '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)
    {
       // $this->detachBehaviors();
        $query = Article::find();
        $query->joinWith(['translations']);
        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);



        if ($this->load($params) && !$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,
            'user_id' => $this->user_id,
            'status' => $this->status,
            'category_id' => $this->category_id,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
        ]);

        $query->andFilterWhere(['like', 'article_translation.title', $this->title])
            ->andFilterWhere(['like', 'article_translation.summary', $this->summary])
            ->andFilterWhere(['like', 'content', $this->content]);

        return $dataProvider;
    }
}

1 个答案:

答案 0 :(得分:0)

如果你想根据连接模型中的关系使用title属性搜索相关模型,你应该声明适当的公共var以允许在搜索模型中使用(并且声明这个$ title也是安全的)例如:

location ~ /(images|userfiles)/ {
    if ($args) {
        # alternative shorthand phpthumb links eg /userfiles/myimage.jpg?w=300
        rewrite .(jpg|jpeg|png|gif)$ /application/third_party/phpThumb/phpThumb.php?src=../../..$uri last;
    }
}