Yii2.0框架模型多表关联查询示例

雨后的草原,野花竞放,像一块刚浸过水的花头巾,连露珠儿也都是五颜六色的了!一条条小河宛如蓝色的缎带缠绕着一望无际的绿色田野,远处一座座造型古朴、色彩和谐的小屋,一派美丽动人的田园风光!

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

希望本文所述对大家基于Yii框架的PHP程序设计有所帮助。

以上就是Yii2.0框架模型多表关联查询示例。做你没做过的事情叫成长,做你不愿意做的事情叫改变,做你不敢做的事情叫突破。更多关于Yii2.0框架模型多表关联查询示例请关注haodaima.com其它相关文章!