Example of multi table association query in Yii 2.0 framework model
- 2021-12-13 07:37:40
- OfStack
In this paper, an example is given to describe the multi-table association query of Yii 2.0 framework model. Share it for your reference, as follows:
Joint table query-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 For User::className() Fields in the table, id For Right::findOne(2) Table field
Multi-table association 1-to-many query optimization
If you use the same query in the same table many times:
\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');
}
Multi-table association 1-to-1 query
\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
// Query all the data of the associated table
$user = User->find()->with('right')->asArray()->all();
For more readers interested in Yii related contents, please check the topics on this site: "Introduction to Yii Framework and Summary of Common Skills", "Summary of Excellent Development Framework of php", "Introduction to smarty Template", "Introduction to php Object-Oriented Programming", "Summary of Usage of php String (string)", "Introduction to php+mysql Database Operation" and "Summary of Common Database Operation Skills of php"
I hope this article is helpful to the PHP programming based on Yii framework.