这期内容当中小编将会给大家带来有关使用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();
上述就是小编为大家分享的使用Yii2.0框架怎么实现一个模型多表关联查询了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注天达云行业资讯频道。