Thinkphp可以进行关联操作,数据库中需要用到join连接查询时候,用thinkPHP框架的关联查询可以有效的提高查询效率,下面是常用的关联:
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 ""
;
print_r($items);
}
comment的模型关联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,如果没有comment里article_id字段,article的数据也不会删除。
comment是多个对应一个article,根据comment关联删除就没有对应的article,我们想要的效果是根据article对应的comment,一对多的删除。
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 "
";
}
}
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 "
";
}
}
注:1、withCount的输出采用“关联方法名_count”,另外withMax()、withMin()、withSum()、withAvg()均可支持这个方法。
2、除了withCount不需要指定字段,其他都要指定统计字段
comment的模型关联article:
//评论表
class Comment extends Model
{
public function article() {
//不设置bind的全部显示
return $this->belongsTo(Article::class)->bind([
"article_title"=>"title"
]);
}
}
控制器:
//使用hasWhere根据article的条件查询(注:comment与article有关联),同时使用with把article查询出来:
public function demo5(){
//方法一
$list = Comment::hasWhere('article',[["title","like","%美国%"]])->with("article")->select()->toArray();
//方法二
$list = Comment::with(['article'=>function($query){
$query->where("title","like","%量子%");
}])->select();
halt($list);
}
注:haswhere的第1个参数模型关联方法名,模型关联方法名和模型名称一样,否则报错