模型操作

通过模型操作数据库,在swoole下自动切换为连接池。在fpm下自动为单列。

插入一条数据

  1. $id = User::insert([
  2. 'name' => $key,
  3. 'email' => 'name@aa.com',
  4. ]);

迭代用户所有的数据

  1. $rs = User::chunk();
  2. foreach($rs as $user){
  3. }

迭代和关系组合使用

  1. User::where('id', '>', 100)
  2. ->where('status', '>', 1)
  3. ->with('category')
  4. ->with('article', [
  5. function ($q) {
  6. $q->with('tags.tag')->with('commmit.user');
  7. }
  8. ])
  9. ->chunk();

插入多条数据

  1. $ar = [];
  2. for ($i = 0; $i < 100; $i++) {
  3. $ar[] = [
  4. 'name' => 'name' . $i,
  5. 'email' => 'name' . $i . '@aa.com',
  6. 'age' => rand(10, 70)
  7. ];
  8. }
  9. User::insert($ar, true);

更新数据

  1. // 先查询后更新 累加
  2. $one = User::find(10);
  3. $row = $one->update(['name' => 'name3s', 'age' => ['age+1']]); // 条件是主键
  4. echo $row . PHP_EOL; // 影响行数
  5. //update users set name='name3s',age=age+1 where id='10'
  6. // 批量更新
  7. $row = User::whereIn('id', [6, 7, 8])->update(['email' => 1423]);
  8. echo $row . PHP_EOL;
  9. // update users set email='123' where id in ('6','7','8')
  10. // 查询出来的对象可以直接调用update
  11. $arr = User::where('id', '>', '20')->orderBy('id asc')->limit(3)->findAll();
  12. foreach ($arr as $v) {
  13. $v->update(['age' => 19]); // 条件是主键
  14. }

删除

  1. $row = User::whereIn('id', [61, 71, 81])->delete();
  2. echo $row . PHP_EOL;// 影响行数
  3. $one = User::find(66);
  4. $row = $one->delete(); // 条件是主键
  5. echo $row . PHP_EOL;

查询

  1. // with 可无限级数关联下去
  2. $arr = User::with('articles.article_tags.tag')->limit(10)->findAll()->toArray();

关联查询

  1. // select * from users left join articles on users.id=articles.user_id where users.id>1
  2. $arr = User::where('users.id', '>', '1')->leftJoin('articles', 'users.id', 'articles.user_id')->findAll()->toArray();
  3. // select * from users left join articles on users.id=articles.user_id and articles.read_count>2 where users.id>1
  4. $arr = User::where('users.id', '>', '1')->leftJoin('articles', function (Join $q) {
  5. $q->on('users.id', 'articles.user_id')->where('articles.read_count', '>', 2);
  6. })->findAll()->toArray();