学习内容:
视频教程:
https://www.kancloud.cn/tpshop/thinkphp5/228862
完全开发手册:https://www.kancloud.cn/manual/thinkphp5/142358
教程中的代码:https://github.com/phpervip/tp5a
一般来说,
建一个评论表,user表与comment表是,一对多关系。
CREATE TABLE tp_comment
(
comment_id
int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT ‘评论id’,
goods_id
mediumint(8) unsigned NOT NULL DEFAULT ‘0’ COMMENT ‘商品id’,
email
varchar(60) NOT NULL DEFAULT ” COMMENT ‘email邮箱’,
username
varchar(60) NOT NULL DEFAULT ” COMMENT ‘用户名’,
content
text NOT NULL COMMENT ‘评论内容’,
add_time
int(10) unsigned NOT NULL DEFAULT ‘0’ COMMENT ‘添加时间’,
ip_address
varchar(15) NOT NULL DEFAULT ” COMMENT ‘ip地址’,
is_show
tinyint(1) unsigned NOT NULL DEFAULT ‘0’ COMMENT ‘是否显示’,
parent_id
int(10) unsigned NOT NULL DEFAULT ‘0’ COMMENT ‘父id’,
user_id
int(10) unsigned NOT NULL DEFAULT ‘0’ COMMENT ‘评论用户’,
img
text COMMENT ‘晒单图片’,
order_id
mediumint(8) DEFAULT ‘0’ COMMENT ‘订单id’,
deliver_rank
tinyint(1) unsigned NOT NULL DEFAULT ‘0’ COMMENT ‘物流评价等级’,
goods_rank
tinyint(1) DEFAULT ‘0’ COMMENT ‘商品评价等级’,
service_rank
tinyint(1) DEFAULT ‘0’ COMMENT ‘商家服务态度评价等级’,
zan_num
int(10) NOT NULL DEFAULT ‘0’ COMMENT ‘被赞数’,
zan_userid
varchar(255) NOT NULL DEFAULT ” COMMENT ‘点赞用户id’,
is_anonymous
tinyint(1) NOT NULL DEFAULT ‘0’ COMMENT ‘是否匿名评价:0不是,1是’,
PRIMARY KEY (comment_id
),
KEY parent_id
(parent_id
),
KEY id_value
(goods_id
)
) ENGINE=InnoDB AUTO_INCREMENT=12238 DEFAULT CHARSET=utf8;
SELECT * FROM tpshop2.0.5
.tp_comment;
model中定义关联方法
// 定义关联方法
public function comm(){
return $this->hasMany('Comment','user_id','id');
}
controller中。
public function test19(){
$user = mUser::get(1);
// 获取User对象的nickname操作
// var_dump($user->nickname);
// 获取User对象的comm关联对象
// 调用属性获取所有comment的集合
$user->comm;
foreach($user->comm as $comm){
// echo "评论id:{$comm->comment_id}用户评论内容:{$comm->content}".'<br/>';
// 执行关联的comm对象的查询,获取User对象的comm关联对象
}
// 关系模型的读取
$comm = $user->comm()->where('content','这东西不错,下次还会来买')->find();
echo "评论id:{$comm->comment_id}用户评论内容:{$comm->content}".'<br/>';
// 关系模型的写入
// 一对多关联新增
// $user = mUser::get(1);
// $comment = new Comment;
// $comment->content = 'ThinkPHP5视频教程';
// $comment->add_time = time();
// $user->comm()->save($comment);
// return '添加评论成功';
// 一对多批量新增
// $user = mUser::get(1);
// $comment = [
// ['content'=>'ThinkPHP视频教程','add_time'=>time()],
// ['content'=>'TP5视频教程','add_time'=>time()]
// ];
//
// $user->comm()->saveAll($comment);
// return '添加comment成功';
// 关联更新
$user = mUser::get(1);
$comm = $user->comm()->getByContent('ThinkPHP5视频教程');
$comm->content = 'ThinkPHP5快速入门';
$comm->save();
}