tp6的with关联使用(删查)

发布时间 2023-05-26 21:27:29作者: djiz

1、with的使用

Thinkphp可以进行关联操作,数据库中需要用到join连接查询时候,用thinkPHP框架的关联查询可以有效的提高查询效率,下面是常用的关联:

  1. hasOne:有一个,A 有一个 B(一对一关联)
  2. hasMany:有很多,A 有很多 B(一对多关联)
  3. belongsTo: 多个(或一个)A 属于 B(属于,相当与多对一)
  4. belongsToMany:多对多关联
    这里有两个表:comment(评论表)、article(文章表)
create table `comment` (
    `id` int primary key AUTO_INCREMENT comment "ID",
    `title` varchar(255) comment '标题',
    `content` text  comment '内容',
)ENGINE=InnoDB DEFAULT CHARSET=utf8;

create table `article` (
    `id` int primary key AUTO_INCREMENT comment "ID",
    `msg` varchar(255) comment '评论内容',
    `article_id` int(10) comment '文章ID',
   `art_sum` int(10)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;

关联查询

comment的模型使用belongsTo()方法关联article表:

//评论表
class Comment extends Model
{
    public function comm() {
        // Article::class关联的表,article_title自定义字段,title显示的字段
        return $this->belongsTo(Article::class)->bind([
            "article_title"=>"title"
        ]);

        //不设置bind的全部显示
//        return $this->belongsTo(Article::class);
    }
}

控制层使用with:

public function demo2(){
   $items = Comment::with(["comm"])->select()->toArray();
    echo "<pre>";
    print_r($items);
}

关联删除

hasMany,一对多

article模型关联comment:

class Article extends Model
{
    //belongsTo是多对一,不适合使用
//    public function comment() {
//        return $this->belongsTo(Comment::class);
//    }

    public function comment() {
        return $this->hasMany(Comment::class,"article_id");
    }
}

together关联删除:

//关联删除
public function demo3(){
    $list = Article::with('comment')->find(1);
    $list->together(["comment"])->delete();
}

除了关联删除和关联查询,还有withCount(关联数量统计的个数):

    //关联查询的数量
    public function demo2(){
        // self::withCount('关联方法名')->select();
        // self::withCount(['关联方法名' => '自定义属性名'])->select();
        $list = Article::withCount('comment')->select();
        foreach($list as $user){
            // 获取文章关联的评论关联个数
            echo $user->comment_count;
            echo "<br>";
        }
    }

withSum(关联数量的相加的结果):

    //关联查询的统计
    public function demo4(){
        //comment的art_sum指定关联统计的字段
        $list = Article::withSum('comment',"art_sum")->select();
        foreach($list as $user){
            // 获取文章关联的评论的art_sum相加的结果
            echo $user->comment_sum;
            echo "<br>";
        }
    }

注:1、withCount的输出采用“关联方法名_count”,另外withMax()、withMin()、withSum()、withAvg()均可支持这个方法。

2、除了withCount不需要指定字段,其他都要指定统计字段

2、hasWhere关联条件查询

源文链接 https://blog.csdn.net/yang_ldgd/article/details/118570184