Thinkphp的关联查询、关联删除

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

(1)hasOne:有一个,A 有一个 B(一对一关联

(2)hasMany:有很多,A 有很多 B(一对多关联

(3)belongsTo: 多个(或一个)A 属于 B属于,相当与多对一

(4)belongsToMany:多对多关联

这里有两个表:comment(评论表)、article(文章表)

#文章
create table article
(
    id int primary key AUTO_INCREMENT comment "ID",
    title varchar(255) comment '标题',
    content text  comment '内容',
)


#评论
create table comment
(
    id int primary key AUTO_INCREMENT comment "ID",
    msg varchar(255) comment '评论内容',
    article_id int comment '文章ID',
)

belongsTo关联查询

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);
    }

关联删除

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

//评论表
class Comment extends Model
{
    public function comm() {
        return $this->belongsTo(Article::class);
    }
}

together关联删除:

    public function demo1(){
        //Comment数据:ID=1,article_id=2,即删除Comment.ID等于1的数据,同时删除article.ID等于2的数据
        $items = Comment::with(["comm"])->find(1);
        $items->together(["comm"])->delete();//删除
    }

从上面可以看到,关联删除根据comment.article_id,如果没有评论article_id字段,文章也不会删除。你想根据文章删除同时评论也要删除,就必须要在article加comment_id字段

猜你喜欢

转载自www.cnblogs.com/bushui/p/13173785.html
今日推荐