Eloquent ORM 之关联查询
小伙伴们好,本文是在我的前一篇随笔的基础上完成的,还没有浏览的同学,请移尊驾哦 Eloquent ORM学习笔记。
前一篇文章用到了leftJoin方法,其实Eloquent对于模块之间的关联查询有自己封装,接下来我们就一起研究Eloquent的关联是如何应用的。
1.创建Models
前一篇文章创建了UserModel,其实对于users_ext也可以创建一个Model: UserExtModel.php
<?php class UserExtModel extends \Eloquent { protected $table = 'users_ext'; protected $primaryKey = 'iAutoId'; protected $connection = 'user'; public function user() { return $this->belongsTo('UserModel','iUserID','iAutoId'); } }
2.建立关联
修改UserModel.php,在文件中添加和users_ext的一对一关联。
1 <?php 2 3 class UserModel extends \Eloquent { 4 5 protected $table = 'users'; 6 protected $primaryKey = 'iAutoId'; 7 protected $connection = 'user'; 8 9 public function userExt(){ 10 return $this->hasOne('UserExtModel','iUserID','iAutoId'); 11 } 12 }
3.关联查询
(1)一对一关联:
上面两个Models利用hasOne()和belongsTo()方法建立的关联模型正是“一对一”模型,现在就可以做出简单的查询:
1 <?php 2 3 class HomeController extends BaseController { 4 5 public function getUsers(){ 6 $resData = UserModel::find(1)->userExt->toArray(); 7 var_dump($resData); 8 exit(); 9 } 10 }
以上查询相当于sql语句:
1 SELECT 2 users_ext.* 3 FROM 4 users 5 LEFT JOIN users_ext ON users.iAutoId = users_ext.iUserID 6 WHERE 7 users_ext.iUserID = 1
(2)一对多关联:
将UserModel模型中hasOne()改为hasMany(),这样就建立了"一对多"的关联模型,现在可以做以下简单查询:
1 <?php 2 3 class HomeController extends BaseController { 4 5 public function getUsers(){ 6 $resData = UserModel::find(1)->userExt()->where('sSex','=',1)->get()->toArray(); 7 var_dump($resData); 8 exit(); 9 } 10 }
以上查询相当于sql语句:
1 SELECT 2 users_ext.* 3 FROM 4 users 5 LEFT JOIN users_ext ON users.iAutoId = users_ext.iUserID 6 WHERE 7 users.iAutoId = 1 8 AND users_ext.sSex = 1
(3)多对多关联:
这个模型相对复杂,就以用户和角色的关系来说明。需要另外创建roles和user_role两张表,并初始化:
1 CREATE TABLE 2 IF NOT EXISTS roles ( 3 iAutoId INT (11) auto_increment, 4 sRoleName VARCHAR (20), 5 PRIMARY KEY (iAutoId) 6 ) ENGINE = INNODB DEFAULT CHARSET = utf8 auto_increment = 1; 7 8 INSERT INTO roles (sRoleName) 9 VALUES 10 ('admin'), 11 ('root'); 12 13 CREATE TABLE 14 IF NOT EXISTS user_role ( 15 iAutoId INT (11) auto_increment, 16 iUserID INT (11), 17 iRoleID INT (11), 18 PRIMARY KEY (iAutoId) 19 ) ENGINE = INNODB DEFAULT CHARSET = utf8 auto_increment = 1; 20 21 INSERT INTO user_role (iUserID, iRoleID) 22 VALUES 23 (1, 1), 24 (1, 2), 25 (2, 1), 26 (3, 2), 27 (3, 1);
紧接着就可以建立RoleModel了:
1 <?php 2 3 class RoleModel extends \Eloquent { 4 5 protected $table = 'roles'; 6 protected $primaryKey = 'iAutoId'; 7 protected $connection = 'user'; 8 }
然后在UserModel中创建“多对多”关联关系:
1 <?php 2 3 class UserModel extends \Eloquent { 4 5 protected $table = 'users'; 6 protected $primaryKey = 'iAutoId'; 7 protected $connection = 'user'; 8 9 public function roles(){ 10 return $this->belongsToMany('RoleModel','user_role','iUserID','iRoleID'); 11 } 12 }
接下来就实现查询了:
1 <?php 2 3 class HomeController extends BaseController { 4 5 public function getUsers(){ 6 7 $resData = UserModel::find(1)->roles; 8 var_dump($resData->toArray()); 9 exit(); 10 } 11 }
以上查询结果为:
好吧,这里只是简单学习了下,还有更复杂的需要小伙伴们自己查看API