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');
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM