1、在模型中,类似多个评论对应一个用户,为一对多的关系
一般来说,关系类型包含了以下几种一对一关联:HAS_ONE 以及相对的 BELONGS_TO一对多关联:HAS_MANY 以及相对的 BELONGS_TO多对多关联:BELONGS_TO_MANY
2、完成模型的步骤主要有:
① 创建User模型② 创建comment 模型(评论模型,以评论为例)③ 在User模型添加方法④ 在comment模型添加方法
3、User模型的代码部分
<?phpnamespace app/index/model;use think/Model;Class User extends Model{//定义关联方法public function comm(){return $this->hasMany('comment','uid','user_id');}}
4、User控制器的代码部分:关系模型的查询
<?phpClass User extends Controller{public function test19(){$user = new User;//获取User对象的属性echo $user->nickname;$user->comm;foreach($user->comm as $comm);echo $comm->comment_id;echo $comm->content;}}
5、关系模型的插入:
<?phpClass User extends Controller{public function test19(){$user = User::get(1);$comment = new Comment;$conment->content = 'tp教程';$conment->add_time = time();$user->comm()->save($conment);return '插入成功'}}
批量插入方法
<?phpClass User extends Controller{public function test19(){$user = User::get(1);$comment = new Comment;$comment=[['content' => 'tp5视频','add_time'=>time()];['content' => '一块钱一个', 'add_time'=>time()];]$user->comm()->save($comment);return '插入成功'}}
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号