PHP code example of leslack-hub / laravel-tools
1. Go to this page and download the library: Download leslack-hub/laravel-tools library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
leslack-hub / laravel-tools example snippets
class Order extends ShardingModel
{
/**
* 分表字段
*/
const SHARDING_COLUMN = 'user_id';
/**
* 获取表名称
*
* @param $userId
*
* @return string
*/
public static function shardingTable($userId)
{
return 'order_' . (int)($userId / 1000000);
}
}
注: where在查询字段 必须与SHARDING_COLUMN一致
Order::create([
'user_id' => $userId,
'order_id' => 'xxxxxx',
]);
连表查询时 需先获取表名
$tableName = Order::shardingTable($userId);
$builder = OrderDetail::query()
->leftjoin($tableName, function ($join) use ($userId, $tableName) {
$join->on('order_detail.id', '=', $tableName . '.order_id')
->where($tableName . '.user_id', '=', $userId)
->where($tableName . '.deleted_at', null);
})
class Order extends MultiShardingModel
{
const SHARDING_COLUMN = 'id';
public static function shardingTable($id)
{
if ($id > 0) {
$num = (int)($id / 20000000);
if ($num < 2) {
return 'sharding_order_id_' . $num;
}
}
return 'order';
}
const SHARDING_COLUMNS = [
'user_id' => [
'condition' => ['id'],
'fill' => ['id','order_id','created_at'],
],
'merchant_id' => [
'condition' => ['id'],
'fill' => ['id','user_id','created_at'],
],
];
public static function shardingByUserId($uid)
{
return 'sharding_order_user_id_' . (int)($uid / 5000000);
}
public static function shardingByMerchantId($merchantId)
{
return 'sharding_order_merchant_id_' . (int)($merchantId / 5000000);
}
}
Order::withTrashed()->shardingWhere('id', 1112)->first()
$orders = order::query()->zoneWhere('user_id', 123)->get();
更新user_id 所有用户订单时间 会同步更新其他主表 或冗余表 deleteAll 方法能够删除
order::query()->zoneWhere('user_id', 123)->updateAll(['created_at' => '2022-01-01 00:00:00']);
switch($type) {
case 1:
$name = 'name_1';
break;
case 2:
$name = 'name_2';
break;
case 3:
$name = 'name_3';
break;
case 4:
$name = 'name_4';
break;
}
// 执行一些业务逻辑
doSomeThing();
switch($type) {
case 1:
$callback = function(){};
break;
case 2:
$callback = function(){};
break;
case 3:
$callback = function(){};
break;
case 4:
$callback = function(){};
break;
}
use LeslackHub\LaravelTools\ArrayService;
$type =1;
$arrayService = new ArrayService([1,2,3,4],['name_1','name_2','name_3','name4'],[function(){},function(){},function(){},function(){}])
$name = $arrayService->getValue('0.'.$type);
$callback = $arrayService->getValue('1.'.$type);
// 增加类型 1 2 3 4 对应的标题
$arrayService->push(['tilte_1','tilte2','title_3','title_4'],'title');
$arrayService->getValue('title.'.$type);