thinkphp5 模型关联和缓存简单实践

来源:互联网 发布:linux项目实战简历 编辑:程序博客网 时间:2024/06/06 05:14

参考资料:
掌握ThinkPHP5.0数据库和模型
ThinkPHP5快速入门
ThinkPHP5.0完全开发手册

模型关联

模型关联还是一个非常方便的一个功能,尤其是查询一个数据需要多个表连接的时候,拼接的sql语句很长,让人很头疼,不过tp5的模型关联正好解决了这个问题。

直接上代码

数据库

sell表
这里写图片描述

country表
这里写图片描述

其中sell表中的place对应着country表中的id

接着创建sell表的模型SellModel和country表的模型CountryModel,

CountryModel

<?phpnamespace app\home\model;use think\Model;class CountryModel extends Model{    protected $table="country";}

SellModel

<?phpnamespace app\home\model;use think\Model;class SellModel extends Model{    protected $table="sell";    protected $autoWriteTimestamp=true;    function country(){       return $this->belongsTo('CountryModel','place','id');    }}

belongsTo(‘关联模型名’,’外键名’,’关联表主键名’,[‘模型别名定义’],’join类型’);

SellModel中有一个关联方法,关联到CountryModel,如果模型不在同一个模块,要添加上命名空间。
还有就是关于hasOne和belongTo的区别在于外键在哪个表中,如果在本表就用belongTo,反之hasOne,
我的外键是place,在本表中,所以用belongTo。

试一下效果

在控制器中

$res=SellModel::all();        foreach ($res as $v){            dump($v->name);            dump($v->country->zh_name);        }

效果
这里写图片描述
把sell表中的name和对应到country表中的zh_name查找出来,这么写很方便

但是通过trace调试可以看到,查找的效率并不是很高,尤其是查找数据多的时候,效率更低
这里写图片描述
每次通过关联方法访问关联表的时候,都会产生一条sql语句

这个时候就要用到关联预载入来提高效率了

$res=SellModel::with('country')->select();        foreach ($res as $v){            dump($v->name);            dump($v->country->zh_name);        }

打印效果是一样的,再看看执行的sql语句
这里写图片描述
这个效率就比没用预载入的高多了

还有一个延迟预载入

        $res=SellModel::all();        $arr=load_relation($res,'country');        foreach ($arr as $v){            dump($v->name);            dump($v->country->zh_name);        }    }

是当需要关联的时候,用load_relation调用关联方法,load_relation是处理数组,load是处理数据集

最后再用缓存优化一下

        //判断是否有这个缓存,就对这个缓存赋值        Cache::remember('sell_list',function (){            return SellModel::with('country')->select();        });        dump(Cache::get('sell_list'));

当然,根据自己的业务逻辑,在有更新和添加操作的时候,缓存也要相应的更新一下。

原创粉丝点击