Yii2.0框架模型多表关联查询示例
程序员文章站
2023-11-18 22:03:28
本文实例讲述了yii2.0框架模型多表关联查询。分享给大家供大家参考,具体如下:
联表查询--hasmany:
use app\models\user;
$r...
本文实例讲述了yii2.0框架模型多表关联查询。分享给大家供大家参考,具体如下:
联表查询--hasmany:
use app\models\user; $right = right::findone(2); //$user = user::find()->where(['right_id' => $right->attributes['id']])->all(); $user = $right->hasmany(user::classname(),['right_id' => 'id'])->all(); //right_id为user::classname()表中字段,id为right::findone(2)表字段
多表关联一对多查询优化
如果多次用到同表相同查询:
\models\rught.php
namespace app\models; use \yii\db\activerecord; class right extends activerecord { public function getusers() { $users = $this->hasmany(user::classname(),['right_id' => 'id'])->asarray()p->all(); return $users; } }
\controller\home\actionabout
public function actionabout() { $right = right::findone(2); // $users = $right->getrights(); $users = $right->rights; dd($users); return $this->render('about'); }
多表关联一对一查询
\models\user.php
namespace app\models; use \yii\db\activerecord; class user extends activerecord { public function getright() { $right = $this->hasone(right::classname,['id' => 'right_id'])->asarray(); return $right; } }
\controller\home\actionabout
$user = user::findone(1); $right = $user->user; dd($right); return $this->render('about');
join
//查询关联表的所有数据 $user = user->find()->with('right')->asarray()->all();