一对一关联:HAS_ONE
一对多关联:HAS_MANY
多对多关联:BELONGS_TO_MANY
1、一对多关联
分别创建users、comment 两个模型
评论模型
namespace app\index\model;
use think\Model;
class Comment extends Model{
}
用户USERS模型
<?php
namespace app\index\model;
use think\Model;
class Users extends Model{
//定义关联方法 一对多
public function comm(){
return $this->hasMany('Comment','uid','user_id'); //comment 评论模型,评论里的uid同users表的user_id 关联。
}
}
在控制器中的使用
//读取数据 一对多
$user = Users::get(1);
//Execute SELECT * FROM `tp_users` WHERE `user_id` = 1 LIMIT 1
echo $user->nickname.'<br>';
//获取User对象的comm关联对象
$result = $user->comm; //这是一个属性不是一个方法所以没有括号 ,评论的对像集合
//Execute SELECT * FROM `tp_comment` WHERE `uid` = 1
foreach ($result as $value){
echo '评论ID:'.$value->comment_id.'评论内容:'.$value->content.'<br>';
}
//带条件执行
$comm = $user->comm()->where('content','你不是个东西')->find();
//SELECT * FROM `tp_comment` WHERE `uid` = 1 AND `content` = '你不是个东西' LIMIT 1
echo '评论ID:'.$comm->comment_id;
$where['uid'] = 1; //评论表里的UID
$where['tp_users.user_id'] = 1; //users 表里的user_id
$user = Users::hasWhere('comm',$where)->select();
//SELECT `Users`.* FROM `tp_users` `Users` INNER JOIN `tp_comment` `Comment` ON `Users`.`user_id`=`Comment`.`uid` WHERE `Users`.`user_id` = 1 AND `Comment`.`uid` = 1 GROUP BY `Users`.`user_id`
2、一对多关联新增
$user = Users::get(1);
$comment = new Comment();
$comment->content = 'ThinkPHP15视频教程';
$comment->add_time = time();
$user->comm()->save($comment);
//INSERT INTO `tp_comment` (`content` , `add_time` , `uid`) VALUES ('ThinkPHP15视频教程' , 1542267794 , 1)
return '添加评论成功!';
3、一对多批量新增
$user = Users::get(1);
$comment=[
['content'=>'ThinkPHP5视频教23程','add_time'=>time()],
['content'=>'as234f','add_time'=>time()],
];
$user->comm()->saveAll($comment);
//INSERT INTO `tp_comment` (`content` , `add_time` , `uid`) VALUES ('ThinkPHP5视频教23程' , 1542267888 , 1)
//INSERT INTO `tp_comment` (`content` , `add_time` , `uid`) VALUES ('as234f' , 1542267888 , 1)