TP5使用模型查詢資料

2021-09-24 13:53:47 字數 2202 閱讀 6413

前提: 引入model

1. get 方法, 引數為 主鍵值

$res = user::get(1);

toarray() 方法是將 get的值,轉為陣列

$res = $res->toarray();

get 方法還支援閉包

$res = user::get(function ($query) );

$res = $res->toarray();

dump($res);

2. 用 where方法

$res = user::where('id', 12)

->field('id, username')

->find();

$res = $res->toarray();

dump($res);

3. all方法, 如果沒有引數,就是查詢所有的資料,如果加入引數,就是主鍵, 可以是'1,2,3'這樣型別的.

$res = user::all();

foreach ($res as $val)

也可以接受乙個陣列, [1,2,3], 也可以接受乙個閉包函式

可以用陣列多條件查詢, 類似於 tp3

$map['name'] = 'imooc';

$map['id'] = array('gt', 2);

$user = user::all($map);

foreach ($user as $val)

dump($data);

$res = user::all(function ($query) );

foreach ($res as $val)

4. value方法, 獲取乙個欄位的值

$res = user::where('id', 20)->value('email');

dump($res);

5.獲取一列資料, 如果只有1個引數,就是需要獲取的列, 如果有第二個引數, 則作為陣列的字首

$res = user::column('email', 'username');

dump($res);

/**array(20) @qq.com"

["imooc_2"] => string(17) "[email protected]"

["imooc_3"] => string(17) "[email protected]"

["imooc_4"] => string(17) "[email protected]"

["imooc_5"] => string(17) "[email protected]"

["imooc_6"] => string(17) "[email protected]"

["imooc_7"] => string(17) "[email protected]"

["imooc_8"] => string(17) "[email protected]"

["imooc_9"] => string(17) "[email protected]"

["imooc_10"] => string(17) "[email protected]"

["imooc_11"] => string(17) "[email protected]"

["imooc_12"] => string(17) "[email protected]"

["imooc_13"] => string(17) "[email protected]"

["imooc_14"] => string(17) "[email protected]"

["imooc_15"] => string(17) "[email protected]"

["imooc_16"] => string(17) "[email protected]"

["imooc_17"] => string(17) "[email protected]"

["imooc_18"] => string(17) "[email protected]"

["imooc_19"] => string(17) "[email protected]"

["imooc_20"] => string(17) "[email protected]"

}**/

TP5使用模型刪除資料

1.靜態方法 destroy,返回受影響的行數,下面的情況是 引數為主鍵的情況 res user destroy 1 dump res 引數也可以是乙個陣列 res user destroy id 2 dump res 引數也可以是乙個閉包函式 res user destroy function q...

tp5 模型關聯

二 文章中用到的表結構 image 表,儲存的位置資訊 banner 推薦位表,儲存推薦位的型別 banner item 表,推薦位中的資訊條目,可以看到它擁有外來鍵 img id theme 表,商品活動主題,包含頭圖,主題圖 product 表,商品表 theme product 表,theme...

tp5 模型查詢構建器問題

情況,在product 模型中倒序查出前二十條最近的資訊 在 模型中定義方法 public function getrecent limit return this order id desc limit limit select 列印出 sql 的樣子是 select from order lim...