<记录>TP5 关联模型使用

在数据库设计中,常常会有如下这种关联模型,分类表中一条分类对应多个商品表中的商品

如果要获得分类表中每条分类 以及 对应的商品的信息,则需要先查询分类表中的数据,然后根据结果遍历查询商品表,最后把数据拼接在一起

TP5中关联模型可以解决这一问题

先创建分类表模型 /application/common/model/Category.php   以及商品表模型 /application/common/model/Goods.php

在分类表中创建关联

namespace app\common\model;

class Category extends Base {

    public function goods(){
        return $this->hasMany('Goods','category_id','id');
    }
}

 接着就可以使用关联模型查询数据

    public function list(){
        return CategoryModel::with('goods')->where(true)->select();
    }

 除了一对多 还可以创建 多对多   一对一

//一对一
hasOne('关联模型','外键','主键');
//多对多
belongsToMany('关联模型','中间表','外键','关联键');

猜你喜欢

转载自www.cnblogs.com/xiaoliwang/p/9348950.html