美文网首页
YII2使用方法之----多表查询

YII2使用方法之----多表查询

作者: 安晓生 | 来源:发表于2019-10-14 18:57 被阅读0次

接下来我们说说框架里面的多表查询。
//这个是在user表进行使用的。一对一的。

 public function getUsercode()
    {
        return $this->hasOne(UserCode::class, ['uid' => 'id']);
    }
//接下来我们这样查询
public function handle()
    {
        $query = User::find()->where(['vip_level'=>1]);

        if ($this->mobile != null) {
            $query->andFilterWhere(['like', 'mobile', $this->mobile]);
        }
        if ($this->created_at) {
            list($start, $end) = explode(' - ', $this->created_at);
            $query->andFilterWhere(['>=', 'created_at', strtotime($start)])
                ->andFilterWhere(['<', 'created_at', strtotime($end)]);
        }
        $query = $query->with([
            'usercode',
        ]);

        return new ActiveDataProvider([
            'query' => $query,
            'pagination' => ['pageSize' => $this->limit],
            'sort' => [
                'defaultOrder' => [
                    'updated_at' => SORT_DESC,
                ],
            ]
        ]);
    }

//还有一种使用法法。
//这样的使用方法怎么调用都行,
//function 下面可以随意写回调。
  public static function view($id)
    {
        return ContentArticle::find()->where('id = :id', [':id' => $id])->with([
            'referrer',
            'product' => function (ActiveQuery $query) {
                $query->with(['product']);
            },
        ])->one();
    }

     public function getProduct()
    {
        return $this->hasMany(ContentArticleProduct::class, ['content_article_id' => 'id']);
    }

    public function getReferrer()
    {
        return $this->hasOne(Referrer::class, ['id' => 'referrer_comment_id']);
    }

相关文章

网友评论

      本文标题:YII2使用方法之----多表查询

      本文链接:https://www.haomeiwen.com/subject/ptcdmctx.html