public function one_one(){// $user = User::find(1); // SELECT * FROM `it_user` WHERE `id` = 1 LIMIT 1// $user = User::where('id',1)->select(); // SELECT * FROM `it_user` WHERE `id` = 1// dump($user);// 完成需求:查找小明的手机号// 1.根据xiaoming查user表 ,条件name=xiaoming, 查询字段id,值是1// 2.根据1查找 userinfo表, 条件user_id = 1, 查询字段tel# select tel from `it_user_info` where user_id=(select id from it_user where name="xiaoming"); 原生#dump( User::query('select tel from `it_user_info` where user_id=(select id from it_user where name="xiaoming")'));$id = User::where('name','xiaoming')->value('id'); // value直接查字段的值$data = UserInfo::where('user_id',$id)->value('tel');dump($data);}
[ DB ] CONNECT:[ UseTime:0.002770s ] mysql:host=127.0.0.1;dbname=relation;charset=utf8
[ SQL ] SHOW COLUMNS FROM `it_user` [ RunTime:0.003472s ]
[ SQL ] SELECT `id` FROM `it_user` WHERE `name` = 'xiaoming' LIMIT 1 [ RunTime:0.000751s ]
[ SQL ] SHOW COLUMNS FROM `it_user_info` [ RunTime:0.002635s ]
[ SQL ] SELECT `tel` FROM `it_user_info` WHERE `user_id` = 1 LIMIT 1 [ RunTime:0.000586s ]
——————————————————————————————————————————————————————
application/index/model/User.php 模型文件
class User extends Model
{// 一对一关联关系public function userInfo(){// 关联的模型名,外键:再对应的关联模型的字段,本模型的主键字段return $this->hasOne('userInfo','user_id','id');}
}
application/index/controller/Index.php 控制器
$user->调用 模型创建的方法 = 这里写方法名同名的属性名即可!
public function one_one_yes(){//使用关联关系模型$user = User::find(1);dump($user->userInfo);
}
控制器
public function info2user1(){/** 第一个参数关联方法名,不是模型名* 第二个参数,数组或者闭包* */$tel='15923456789';/*闭包传值必须使用 use($tel)*//*$user = User::hasWhere('userInfo',function($query) use($tel){$query->where('tel',$tel);})->select();*/$user = User::hasWhere('userInfo',['tel'=>$tel])->select();dump($user);}
[ DB ] CONNECT:[ UseTime:0.002286s ] mysql:host=127.0.0.1;dbname=relation;charset=utf8
[ SQL ] SHOW COLUMNS FROM `it_user` [ RunTime:0.002652s ]
[ SQL ] SELECT `User`.* FROM `it_user` `User` INNER JOIN `it_user_info` `UserInfo` ON `User`.`id`=`UserInfo`.`user_id` WHERE `UserInfo`.`tel` = '15923456789' [ RunTime:0.001156s ]