二、文章中用到的表結構
image 表,儲存的位置資訊
banner 推薦位表,儲存推薦位的型別
banner_item 表,推薦位中的資訊條目,可以看到它擁有外來鍵 img_id
theme 表,商品活動主題,包含頭圖,主題圖
product 表,商品表
theme_product 表, theme 與 product 的中間表
可以建立以下的 e-r圖,乙個 banner可以用有多個 banner_item,乙個banner_iten 擁有乙個 image;
theme 與 product 是多對多關係,
圖1 表之間關係
三、從問題出發講解關聯
(1)查詢 banner 幷包含其下的 banner_item
由圖1可知,我們要在 banner 與 banner_item 之間建立一對多的關聯關係
class banner extends model
public static function getbannerbyid($id)
}
查詢資料可得以下結果
,
,
,
]
}
可以發現,在 items 下為乙個陣列,說明乙個 banner 包含多個 banner_item ,有乙個問題, items下面是 img_id,客戶端需要路徑,不需要 img_id,所以我們還需要建立 banneritem 與 image 模型間的關係。這時,banner 與 banneritem有一對多關聯,banneritem 與 image 有一對一關聯,這種關聯在 tp5 中稱為巢狀關聯。繼續完善**。
banneritem.php
class banneritem extends model
}
banner.php
class banner extends model
public static function getbannerbyid($id)
}
這裡 items.img 這種語法並不太好理解,我們可以根據語境解釋,在乙個 banner 下需要包含多個 banneritem,而每個 banneritem 下面又對應乙個 image。
查詢結果:
},
},
},
}
]
}
這樣的結果就可以被客戶端處理了。
(2)hasone 與 belongsto 的區別
一對一關係,存在主從關係(主表和從表 ),主表不包含外來鍵,從表包含外來鍵。
hasone 和 belongsto 都是一對一關係,區別:
在主表的模型中建立關聯關係,用 hasone
在從表模型中建立關聯關係,用 belongsto
所以,我們在 banneritem 中建立與 image 的關係,用的是 belongsto ,而不是 hasone。相反,如果想在 image 中查詢到 banneritem 的內容,需要用 hasone 。
(3)查詢 theme 幷包含其下的 product
為了讓查詢的主題包含,所以我們要建立 theme 與 product 和 image 的關聯關係,theme 中 topic_img_id 和 head_img_id 與 image 的 id 都是一對一的關係,theme 與 product 是多對多關聯。
class theme extends model
public function headimg()
/**
* 建立多對多關聯模型
* @return \think\model\relation\belongstomany
*/
public function products()
/** * 返回 theme和poducts * @id theme id * @return theme資料模型 */
public static function getthemewithproducts($id)
}
查詢結果為
[
,
"head_img":
},
,
"head_img":
},
,
"head_img":
}
]
可以看到,有的屬性前端並不需要使用,比如 topic_img_id,delete_time等,所以還需要隱藏字段
在 theme.php 中加入
protected $hidden = ['topic_img_id', 'head_img_id', 'delete_time', 'update_time'];
這裡只是結合例子,講了關聯模型的簡單使用。祝大家學習愉快。 有關TP5 模型關聯隨筆
一對一關聯 hasone 關聯模型 外來鍵 主鍵 關聯模型 必須 關聯的模型名或者類名 外來鍵 預設的外來鍵規則是當前模型名 不含命名空間,下同 id 例如user id 主鍵 當前模型主鍵,缺省會自動獲取也可以指定傳入 一對多關聯 hasmany 關聯模型 外來鍵 主鍵 關聯模型 必須 模型名或者...
例項講解TP5中關聯模型
二 文章中用到的表結構 image 表,儲存的位置資訊 banner 推薦位表,儲存推薦位的型別 banner item 表,推薦位中的資訊條目,可以看到它擁有外來鍵 img id theme 表,商品活動主題,包含頭圖,主題圖 product 表,商品表 theme product 表,theme...
TP5隱藏關聯屬性字段
環境thinkphp5 php7.0.10 我們通常會隱藏一些字段,應用於不同的介面 先將database的配置檔案更改,將資料集返回型別改為collection 下面我們的介面的查詢不管是find 還是select 都一樣處理 group group hidden name group是mode查...