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