Yii2.0 model基本操作(连表操作)

来源:互联网 发布:淘宝类目上限数量 编辑:程序博客网 时间:2024/06/07 20:16
<!-- 连表model -->class Ls extends ActiveRecord{//重命名表名 %为前缀名public static  function tableName()    {        return '{{%news}}';    }    //设置主键(当前model不为主键值) //    public static function primaryKey(){ //    return ['key'=>'id'];// }      public function getNews()    {    return $this->hasOne(cnt::className(),['id' => 'id']);    }        public function getCategory()    {        return $this->hasOne(ly::className(),['catid'=>'catid']);    }    }
控制器连表写法
$data=ls::find()->joinWith(['news'])->alias('a')->joinWith('category')->where(['a.id'=>$id])->asArray()->all();
未使用model层的写法
$query->select(['user.name AS author', 'post.title as title'])->from('user')->leftJoin('post', 'post.user_id = user.id');
原创粉丝点击