Thinkphp模型关联条件查询

Thinkphp常常需要关联操作,数据库中需要用到join连接查询,根据对方的条件进行关联条件查询

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

Thinkphp模型关联条件查询Thinkphp模型关联条件查询

 

 

 

 

 

 

 

模型:

//评论表
class Comment extends Model
{
    public function article() {
        //不设置bind的全部显示
        return $this->belongsTo(Article::class)->bind([
            "article_title"=>"title"
        ]);
    }
}

方法一:hasWhere关联条件查询:

    public function demo5(){
        //使用hasWhere根据article的条件查询(注:comment与article有关联),同时使用with把article查询出来:
        $list = Comment::hasWhere(‘article‘,[["title","like","%美国%"]])->with("article")->select()->toArray();
        

     //或者,效果一样 $list = Comment::with([‘article‘=>function($query){ $query->where("title","like","%量子%"); }])->select(); }

sql语法:

SELECT * FROM `comment` `Comment` INNER JOIN `article` `Article` ON `Comment`.`article_id`=`Article`.`id` 
WHERE `Article`.`title` LIKE %美国%

方法二:withJoin关联条件查询:

    public function demo5(){
        $comm = Comment::withJoin("article")->where("article.title","like","%美%")->select()->toArray();
    }

sql语法:

SELECT * FROM `comment` `comment` INNER JOIN `article` `article` ON `comment`.`article_id`=`article`.`id` 
WHERE `article`.`title` LIKE %美%

方法三:Join直接使用:

    public function demo5(){
        $comm = Db::name("Comment")
            ->alias("c")
            ->join("article a","a.id = c.article_id")
            ->where("a.title","like","%量子%")
            ->select()
            ->toArray();
    }

注:1、haswhere的第1个参数模型关联方法名,和模型名称(article)一样,否则报错

  2、withJoin第1个参数模型关联方法名,要和模型名称article)一样,否则报错

  3、withJoin和haswhere默认是inner join

 

Thinkphp模型关联条件查询

上一篇:快速了解Kubernetes


下一篇:css对文字的设置