TP5使用模型查询数据

前提: 引入model

use app\index\model\User;

1. get 方法, 参数为 主键值

 $res = User::get(1);

 toArray() 方法是将 get的值,转为数组

$res = $res->toArray();

get 方法还支持闭包

$res = User::get(function ($query) {
    $query->where('username', 'eq', 'imooc_10')
        ->field('username, email');
});

$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) {
    dump($val->toArray());
}

也可以接受一个数组, [1,2,3], 也可以接受一个闭包函数

可以用数组多条件查询, 类似于 tp3

$map['name'] = 'imooc';
$map['id']   = array('gt', 2);
$user        = User::all($map);


foreach ($user as $val) {
    $data[] = $val->toArray();
}

dump($data);
$res = User::all(function ($query) {
    $query->where('id', '<', 5)
        ->field('id, username');
});
foreach ($res as $val) {
    dump($val->toArray());
}

4. value方法, 获取一个字段的值

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

5.获取一列数据, 如果只有1个参数,就是需要获取的列, 如果有第二个参数, 则作为数组的前缀

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

/**
array(20) {
  ["imooc_1"] => string(17) "imooc_{$i}@qq.com"
  ["imooc_2"] => string(17) "imooc_{$i}@qq.com"
  ["imooc_3"] => string(17) "imooc_{$i}@qq.com"
  ["imooc_4"] => string(17) "imooc_{$i}@qq.com"
  ["imooc_5"] => string(17) "imooc_{$i}@qq.com"
  ["imooc_6"] => string(17) "imooc_{$i}@qq.com"
  ["imooc_7"] => string(17) "imooc_{$i}@qq.com"
  ["imooc_8"] => string(17) "imooc_{$i}@qq.com"
  ["imooc_9"] => string(17) "imooc_{$i}@qq.com"
  ["imooc_10"] => string(17) "imooc_{$i}@qq.com"
  ["imooc_11"] => string(17) "imooc_{$i}@qq.com"
  ["imooc_12"] => string(17) "imooc_{$i}@qq.com"
  ["imooc_13"] => string(17) "imooc_{$i}@qq.com"
  ["imooc_14"] => string(17) "imooc_{$i}@qq.com"
  ["imooc_15"] => string(17) "imooc_{$i}@qq.com"
  ["imooc_16"] => string(17) "imooc_{$i}@qq.com"
  ["imooc_17"] => string(17) "imooc_{$i}@qq.com"
  ["imooc_18"] => string(17) "imooc_{$i}@qq.com"
  ["imooc_19"] => string(17) "imooc_{$i}@qq.com"
  ["imooc_20"] => string(17) "imooc_{$i}@qq.com"
}
**/

 

你可能感兴趣的:(TP5)