Yii2中关联查询简单用法示例

原创 2016-12-29 15:51:24 238
摘要:本文实例讲述了Yii2中关联查询用法。分享给大家供大家参考,具体如下:有两张表,post和category,post.cate_id对应category.id使用Gii上升这两张表的model然后post的model中有如下代码public function getCate() {   return $this->hasOne(Categor

本文实例讲述了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();
}

 更多关于Yii2中关联查询简单用法示例请关注PHP中文网(www.php.cn)其它文章!  


发布手记

热门词条