1. 程式人生 > >TP5 關聯模型使用(巢狀關聯、動態排序以及隱藏欄位)

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