redis

$redis = \Yii::$app->redis;
$res = $redis->get('ttp:00d716905c8ed414aa0103ba17815795');
$res = unserialize($res);
return $this->asJson($res);


$redisKey = "yixinzuqiu:houtai:messge:infoMessage:{$id}";
$data = Redis::connection('plan')->get($redisKey);
if ($data){
$data = json_decode($data);
return json_encode(['data' => $data]);
}


Redis::connection('plan')->setex($redisKey, 60, json_encode($info));

MSQYL

输出刚刚执行的 SQL

<?php


use Hyperf\DbConnection\Db;
use Hyperf\Utils\Arr;
use App\Model\Book;


// 启用 SQL 数据记录功能
Db::enableQueryLog();


$book = Book::query()->find(1);


// 打印最后一条 SQL 相关数据
var_dump(Arr::last(Db::getQueryLog()));​

自动管理数据库事务

你可以使用 ​​Db​​​ 的 ​​transaction​​​ 方法在数据库事务中运行一组操作。如果事务的闭包 ​​Closure​​​ 中出现一个异常,事务将会回滚。如果事务闭包 ​​Closure​​​ 执行成功,事务将自动提交。一旦你使用了 ​​transaction​​ , 就不再需要担心手动回滚或提交的问题:

<?php
use Hyperf\DbConnection\Db;

Db::transaction(function () {
Db::table('user')->update(['votes' => 1]);

Db::table('posts')->delete();
});

子查询,原生语句执行

$changeIndexList = Db::select(' SELECT * FROM (SELECT `id`,`match_id`,`sample_data`,`odds_index`,`type` 
FROM `bifen`.`bifen_index_discrete` WHERE `match_id` = ? ORDER BY `id` DESC ) a
GROUP BY `type` ORDER BY `id` DESC,type DESC', [$matchId]);

orwhere whereor

$db = $db->whereIn("home_team_id", $teamIdSearch)    
->orWhere(function ($query) use ($teamIdSearch, $startTime, $endTime, $competitionId) {
$query->whereBetween("match_time", [$startTime, $endTime])
->whereIn("away_team_id", $teamIdSearch);
if ($competitionId) {
$query->where("competition_id", $competitionId);
}
});

定义空对象

$result = new \stdClass();

获取记录某值

$value->gzh_name = WechatIndex::query()
->where('id', $value->gzh_id)
->value('name');

数组idarr

$userIdArray = StoreUser::query()
->where('is_register', 1)
->pluck('user_id')
->toArray();
$userIdArray = array_unique($userIdArray);

$compensationList = Compensation::query()
->select('id', 'similar') ->whereIn('id', $matchIdArr)
->get()
->toArray();
$midArr = array_unique(array_column($drfinpayzb1List, 'mid'));
$ids = "'" . implode("','", $midArr) . "'";
$drfinpayList = m('drfinpay')->getall("id in (" . $ids . ")", 'id,expensetype');
//创建人
$userIdArray = array_unique(array_column($list, 'created_user_id'));
$userList = (new ZucaiBackendUser())->getListByIdArr($userIdArray);
<?php

declare (strict_types=1);

namespace App\Model;

use Hyperf\DbConnection\Model\Model;


class ZucaiBackendUser extends Model
{
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'zucai_backend_user';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [];


public function getListByIdArr($idArr)
{
$list = self::select('id', 'user_name')
->whereIn('id', $idArr)
->get()
->toArray();

$data = [];
foreach ($list as $value) {
$data[$value['id']] = $value;
}

return $data;
}

}