Blogger Information
Blog 250
fans 3
comment 0
visits 323130
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
thinkphp5:关联模型|什么是一对多
梁凯达的博客
Original
1513 people have browsed it

1、在模型中,类似多个评论对应一个用户,为一对多的关系

  1. 一般来说,关系类型包含了以下几种
  2. 一对一关联:HAS_ONE 以及相对的 BELONGS_TO
  3. 一对多关联:HAS_MANY 以及相对的 BELONGS_TO
  4. 多对多关联:BELONGS_TO_MANY

2、完成模型的步骤主要有:

  1. 创建User模型
  2. 创建comment 模型(评论模型,以评论为例)
  3. User模型添加方法
  4. comment模型添加方法

3、User模型的代码部分

  1. <?php
  2. namespace app/index/model;
  3. use think/Model;
  4. Class User extends Model{
  5. //定义关联方法
  6. public function comm(){
  7. return $this->hasMany('comment','uid','user_id');
  8. }
  9. }

4、User控制器的代码部分:关系模型的查询

  1. <?php
  2. Class User extends Controller{
  3. public function test19(){
  4. $user = new User;
  5. //获取User对象的属性
  6. echo $user->nickname
  7. $user->comm;
  8. foreach($user->comm as $comm);
  9. echo $comm->comment_id;
  10. echo $comm->content;
  11. }
  12. }

5、关系模型的插入:

  1. <?php
  2. Class User extends Controller{
  3. public function test19(){
  4. $user = User::get(1);
  5. $comment = new Comment;
  6. $conment->content = 'tp教程';
  7. $conment->add_time = time();
  8. $user->comm()->save($conment);
  9. return '插入成功'
  10. }
  11. }

批量插入方法

  1. <?php
  2. Class User extends Controller{
  3. public function test19(){
  4. $user = User::get(1);
  5. $comment = new Comment;
  6. $comment=[
  7. ['content' => 'tp5视频','add_time'=>time()];
  8. ['content' => '一块钱一个', 'add_time'=>time()];
  9. ]
  10. $user->comm()->save($comment);
  11. return '插入成功'
  12. }
  13. }
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post