日志-2019年11月

2019-11-1 周五

可以为空的请求验证一定要记得加上 nullable

2019-11-4 周一

使用 Metabase 导出至网页:

2019-11-5 周二

Laravel 5.5 BUG

alpha_num -> 验证的字段必须完全是字母、数字。
然而实际上中文也能够通过验证
正确的方式是使用正则表达式来验证:

'account' => array(
                'nullable',
                'regex:/^[A-Za-z0-9]+$/',
                'max:256',
            ),

2019-11-6 周三

修改数据库用户的验证方式为 MYSQL 原生验证

mysql -u root -p

select host,user,plugin,authentication_string from mysql.user;

ALTER USER 'root'@'%' IDENTIFIED WITH mysql_native_password BY '00000000';

2019-11-7 周四

正则表达式

匹配中文的时候,需要在后面加上一个 u 表示这是 UTF-8 字符集

// 匹配字符串中包含中文
$a = '/[\x{4e00}-\x{9fa5}]/u';
$str = "1cd";
preg_match($a, $str);

2019-11-8 周五

Redis 配置

使配置文件生效

Portainer 中:
Command 里填写 'redis-server' '/data/redis.conf'
Volumes 里的 /data 指向 Docker 里的 Volume

设置密码:

requirepass PASSWORD

设置可以远程访问

# bind 127.0.0.1

2019-11-9 周六

验证日期比较:

after:date
after_or_equal:date
before:finish_date
before_or_equal:date
date_equals:date
date_format:format

示例:

public function rules()
{
    return [
        'content' => 'required|string',
        'start_date' => 'required|date|before:finish_date',
        'finish_date' => 'required|date',
        'link' => 'required|string',
        'is_https' => 'required|integer|in:0,1',
    ];
}

public function messages()
{
    return [
        'content.required' => '轮播内容必填',
        'start_date.required' => '轮播开始日期必填',
        'finish_date.required' => '轮播结束日期必填',
        'link.required' => '跳转链接必填',
        'is_https.required' => 'HTTP协议必填',
        'start_date.before' => '开始日期必须在结束日期之前',
    ];
}

设置日期格式

 date('Y.m.d', strtotime($this->start_date))

2019-11-11 周一

Array 类型进行筛选:

$combos = BIZPointsBill::COMBOS;
$combosCost = array_filter($combos, function ($item) {
    return $item['biz_point_total'] == 50;
})[0]['cost'];

2019-11-12 周二

Json 数据存入 Redis 中:

def get_zhihu2():
    res = requests.get('https://www.zhihu.com/api/v3/feed/topstory/hot-list-web?limit=50', headers=headers)
    m = json.loads(res.text)
    counter = 1
    if len(m['data']) == 50:
        # sql_clean('z')
        for c in m['data']:
            content = c['target']['title_area']['text']
            heat = int(1.07 ** (50 - counter))
            salt = ''.join(random.sample(string.ascii_letters + string.digits, 32))
            print(salt + ' ' + str(counter) + ' ' + content + ' ' + str(heat))
            # sql_save(salt, str(counter), content, str(heat), 'z')
            r.set(content, salt, ex=500)
            qq = json.dumps({"id": salt, "heat": str(heat), "source": 'z', "calculate_time": str(datetime.datetime.now())})
            r.set(content, qq, ex=500)
            counter += 1

2019-11-13 周三

Redis 服务启动与关闭

# redis关闭
redis-cli -h 127.0.0.1 -p 6379 shutdown

# redis启动
redis-server

2019-11-14 周四

MySQL DUAL

执行插入的时候需要检查是否存在,例如:

# 添加如何获取账号页面
INSERT INTO `articles` (`id`, `page`, `type`, `name`, `pic_url`, `content`, `created_by`)
SELECT 200, 'about', '运营', '如何获取账号', '', '我也不知道', 1 FROM DUAL
WHERE NOT EXISTS (SELECT `id` FROM `articles` WHERE `id` = 200);

这里有一个 DUAL 表,是一个虚拟表,官网上给出的例子能够很好的展示它的用途:

mysql> SELECT 1 + 1;
        -> 2

mysql> SELECT 1 + 1 FROM DUAL;
        -> 2

DUAL is purely for the convenience of people who require that all SELECT statements should have FROM and possibly other clauses. MySQL may ignore the clauses. MySQL does not require FROM DUAL if no tables are referenced.

MySQL 8.0 官方文档

2019-11-15 周五

MySQL 查找最长的一条字段的记录

SELECT
    *,
    length( `title` ) 
FROM
    `orders` 
WHERE
    length( `title` ) = ( SELECT max( length( `title` )) FROM `orders` );

2019-11-18 周一

日期的比较

Carbon::today()->greaterThan(Carbon::createFromFormat('Y-m-d', $this->start))

2019-11-19 周二

String 类型的 "3*3" 计算为 9

/**
 * 计算面积
 *
 * @param $size
 *
 * @return float|int|null
 */
private function getArea($size)
{
    try {
        return (float)str_before($size, '*') * (float)str_after($size, '*');
    } catch (\Exception $exception) {
        return null;
    }
}

2019-11-20 周三

项目 -> 场地

physical resource -> selling resource

2019-11-21 周四

变更记录,记录进Comment

<?php
namespace App\Models\Records;
class AAAAA extends BaseRecords
{
    public function recordMappings(): array
    {
        $this->setComment($this->request->input('modify_reason', null));

2019-11-22 周五

单元测试示例:

/**
 * Class AAAControllerTest
 * @package Tests\Feature\V1\AAA
 * @coversDefaultClass \App\Http\Controllers\Api\AAAController
 */
class AAAControllerTest extends TestCase
{
    /**
     * @test 测试首页
     * @covers ::index
     */
    public function testIndex()
    {
        $response = $this->user(1)
            ->version('v1')
            ->json('GET', '/api/index');

        $this->prettyPrint($response);
        $this->assertTrue(in_array($response->original['code'], [1, -2002]));
    }
}

2019-11-23 周六

Collection 相关操作

将两个集合合并:

$collection = collect([$fieldOrderItems, $bizPointsOrders]);
$collection = $collection->collapse();

集合排序:

$collection = $collection->sortBy('paid_at')->values();

集合分页:

$collection = new Paginator($collection, $request->per_page, $request->page, ['path' => $request->url()]);

2019-11-25 周一

通过关联关系保存数据

// 保存视频
$community->community_video()->delete();
if ($video = $communityStore->community_video) {
    $community_video = new CommunityResourceImg();
    $community_video->pic_url = $video['pic_url'];
    $community_video->seq = $video['seq'] ?? 1;
    $community_video->type = CommunityResourceImg::VIDEO;

    $community->community_video()->save($community_video);
}

2019-11-26 周二

只返回需要的字段

'community_invite_ppt' => $this->community_invite_ppt()->get(['title', 'pic_url']),

2019-11-27 周三

MySQL 修改字段备注

# 备注修改
ALTER TABLE `imgs` modify column `type` tinyint comment '备注备注';

2019-11-28 周四

MySQL 查询存在与否

if (Order::where('enterprise_id', '=', $enterpriseId)
    ->where('order_type', '=', Order::ORDER_TYPE_A)
    ->where('pay_type', '=', Order::PAY_TYPE_BANK)
    ->where('status', '=', Order::ORDER_NEED_CONFORM)
    ->exists()
) {
    return self::NEED_CONFIRM;
}

2019-11-29 周五

单元测试验证还可以这样:

function testStore()
{
    $response = $this->user(1)
    ->version('v1')
    ->json('POST', 'api/test', [
        'id' => 1,
        'name' = '小明'
    ])

    $response->assertJsonFragment([
        'code' => 1
    ]);
}