TP5 关联模型使用(嵌套关联、动态排序以及隐藏字段)

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

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

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

普通关联

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

在分类表中创建关联

class Category extends Base {

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

控制器中调用

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

 嵌套关联

 

模型Category.php

class Category extends Model
{
    public function product(){
        return $this->hasMany('product','category_id','id');
    }
}

模型Goods.php

class Product extends Model
{
    public function property(){
        return $this->hasMany('property','goods_id','id');
    }
}

在控制器中调用:

public function index()
    {
        return Category::with('product,product.property')->where('id',1)->find();
    }

在调用关联模型查询数据时,如果我们需要动态隐藏字段,或者给记录排序时可以这么做

 

复制代码
class Category extends Model
{
    public function product(){
        return $this->hasMany('product','category_id','id');
    }

    public function list(){
        //在with中可以传递一个闭包函数,函数的参数为当前key锁对应模型的查询器 $this
        //在闭包函数中无需使用select或者find等返回数据
        //如下操作返回 category中所有值,以及对应 product ,并且product按照price排序
        return self::with([
            'product'=>function($query){
                $query->with('property')->field('name')->order('price');
            }
        ])->select();
    }
}
复制代码

建立原则

1. 哪张表中建立外键那么那张表就是从表  

2. 理论上可以在关联的两张表中建立关联关系,例如用户表User 和用户信息表 Profile 是一对一的关系,假设在Profile表中user_id字段指向User表的id字段,那么在User表中可以建立外键

public function profile(){
     return $this->hasOne('profile','user_id','id');  
}

也可以在Profile表中建立

public function user(){
      return $this->belongsTo('user','user_id','id');
}

 

posted @   爱跑步的乌龟  阅读(3501)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示