Yii2中關(guān)聯(lián)查詢簡單用法示例

字號:


    本文實例講述了Yii2中關(guān)聯(lián)查詢用法。分享給大家供大家參考,具體如下:
    有兩張表,post和category,post.cate_id對應(yīng)category.id
    使用Gii上升這兩張表的model
    然后post的model中有如下代碼:
    public function getCate()
    {
      return $this->hasOne(Category::className(), ['id' => 'cate_id']);
    }
    在post這個model最下面在添加如下方法即可獲取關(guān)聯(lián)表內(nèi)容:
    public static function getPostsByCategory($cate_id)
    {
      return Post::find()
        ->joinWith('cate')
        ->where(['post.cate_id'=>$cate_id])
        ->asArray()
        ->all();
    }
    希望本文所述對大家基于Yii框架的PHP程序設(shè)計有所幫助。