laravel筆記+資料庫操作

ShariseMo發表於2018-08-15

資料庫操作

更新:

DB::table('contacts')
    ->where('id', 1)
    ->update(['meta->wants_newsletter' => false]);複製程式碼

查詢:

$query = Goods::where([
    'business_no' => $this->business_no,
    'is_delete'   => 0,
]);// 關鍵詞查詢
if ($request->filled('keyword')) {
    $query->where(function ($query) use ($request) {
        $query->orWhere('goods_name', 'like', '%' . $request->keyword . '%')
            ->orWhere('goods_model_no', 'like', '%' . $request->keyword . '%')
            ->orWhere('goods_sn','like','%' . $request->keyword . '%');
    });
}複製程式碼

SQL語句

// 分組查詢
$store_arr = $query
    ->select(DB::raw('count(*) as user_count, sum(order_fact_money) as amount, store_id, order_fact_money'))
    ->groupBy('store_id')
    ->get()->toArray();複製程式碼
SELECT 
SUM(CASE WHEN MONTH(s.CreateTime) = 1 THEN s.Amount ELSE 0 END) AS '一月',
SUM(CASE WHEN MONTH(s.CreateTime) = 2 THEN s.Amount ELSE 0 END) AS '二月',
SUM(CASE WHEN MONTH(s.CreateTime) = 3 THEN s.Amount ELSE 0 END) AS '三月',
SUM(CASE WHEN MONTH(s.CreateTime) = 4 THEN s.Amount ELSE 0 END) AS '四月',
SUM(CASE WHEN MONTH(s.CreateTime) = 5 THEN s.Amount ELSE 0 END) AS '五月',
SUM(CASE WHEN MONTH(s.CreateTime) = 6 THEN s.Amount ELSE 0 END) AS '六月',
SUM(CASE WHEN MONTH(s.CreateTime) = 7 THEN s.Amount ELSE 0 END) AS '七月',
SUM(CASE WHEN MONTH(s.CreateTime) = 8 THEN s.Amount ELSE 0 END) AS '八月',
SUM(CASE WHEN MONTH(s.CreateTime) = 9 THEN s.Amount ELSE 0 END) AS '九月',
SUM(CASE WHEN MONTH(s.CreateTime) = 10 THEN s.Amount ELSE 0 END) AS '十月',
SUM(CASE WHEN MONTH(s.CreateTime) = 11 THEN s.Amount ELSE 0 END) AS '十一月',
SUM(CASE WHEN MONTH(s.CreateTime) = 12 THEN s.Amount ELSE 0 END) AS '十二月'
FROM Orders AS s
WHERE YEAR(s.CreateTime) = 2014

select sum(case when create_time between 132324324 and 123221324 then order_money else 0) as '1月'複製程式碼
    /**
     * 計算時間區間
     * @param string $unit
     * @return array
     */
    private function computeTimeRange($unit = 'day')
    {
        if ($unit == 'month') Carbon::useMonthsOverflow(false);
        $now = Carbon::now();

        $func       = ucfirst($unit);
        $sub_func   = 'sub' . $func;
        $start_func = 'startOf' . $func;
        $end_func   = 'endOf' . $func;

//        $range = [$now->$start_func()->toDateString() => [$now->$start_func()->timestamp, $now->$end_func()->timestamp]];
        $range = [$now->$start_func()->toDateString() => [$now->$start_func()->toDateTimeString(), $now->$end_func()->toDateTimeString()]];
        for ($i = 0; $i < 17; $i++) {
            $day = $now->$sub_func();
//            $range[$day->$start_func()->toDateString()] = [$day->$start_func()->timestamp, $day->$end_func()->timestamp];
            $range[$day->$start_func()->toDateString()] = [$day->$start_func()->toDateTimeString(), $day->$end_func()->toDateTimeString()];
        }

        return $range;
    }
//呼叫
   public function getPerformChart(IdCountRequest $request){
        $time_unit  = $request->filled('time_unit') ? $request->time_unit : 'day';
        $time_range = $this->computeTimeRange($time_unit);

        $sql = [];
        $str = 'sum(case when {column_name} between "%s" and "%s" then order_fact_money else 0 end) as "%s"';

        foreach ($time_range as $key => $item) {
            $sql[] = sprintf($str, $item[0], $item[1], $key);
        }
        $sql = implode(',', $sql);

        // 總業績
        $query = OrderOffline::query()->where(['business_no' => $this->business_no, 'is_delete' => 0]);
//        $query->where('is_followed', '>', 0);
        if ($request->filled('store_id')) {
            $query->where('store_id', $request->store_id);
        }
        $income = $query->select(DB::raw(str_replace('{column_name}', 'order_time', $sql)))->first();

        return $income->toArray();
    }
複製程式碼

關聯操作

Eloquent 假設外來鍵應該在父級上有一個與之匹配的 id(或者自定義 $primaryKey),換句話說,Eloquent 將會通過 user 表的 id 值去 phone 表中查詢 user_id 與之匹配的 Phone 記錄。如果你想要關聯關係使用其他值而不是 id,可以傳遞第三個引數到hasOne 來指定自定義的主鍵:

return $this->hasOne('App\Phone', 'foreign_key', 'local_key');
return $this->hasOne('App\Phone', 'user_id', 'id');    

return $this->belongsTo(Store::class, 'foreign_key', 'owner_key');
return $this->belongsTo(Store::class, 'store_id', 'id');

複製程式碼

關聯關係:hasOne,hasMany

反向關聯:belongsTo,belongsToMany

處理資料方法

// 陣列轉XML
public function arrayToXml($arr){
   $xml = '<xml>';      //  $xml = '&lt'.'xml'.'&gt';
   foreach ($arr as $key=>$val){
      $xml=$xml."&lt".$key."&gt".$val."&lt/".$key."&gt"; 
      //$xml=$xml."<".$key.">".$val."</".$key.">";
   }
   $xml=$xml.'&lt'.'/xml'.'&gt';   // $xml= $xml.'</xml>';
   return $xml;
}複製程式碼
// 使用curl方法呼叫微信介面
$url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
//設定標頭檔案的資訊作為資料流輸出
curl_setopt($curl, CURLOPT_HEADER, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, Array("Content-Type:text/xml; charset=utf-8"));    // 一定要定義content-type為xml,要不然預設是text/html!
//設定獲取的資訊以檔案流的形式返回,而不是直接輸出。
curl_setopt($curl, CURLOPT_RETURNTRANSFER,1);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $xmlData);
$res = curl_exec($curl);
curl_close($curl);複製程式碼



資料庫---索引

  • 索引是表示資料的另一種方式,它提供的資料順序不同於資料在磁碟上的物理儲存順序
  • 索引的特殊是在表內重新排列記錄的物理位置。
  • 索引可建立在資料表的一個或者多個列上,或建立在表的幾列組合上。每個索引都會被起個名字
  • 索引被建立於已有表中,可以使對行的定位更快速更有效。使用者無法看到索引,它們只能被用來加速查詢
  • 更新一個包含索引的表需要比更新一個沒有索引的表花費更多的時間,這是因為索引本身也需要更新。因此,理想的做法是僅僅在常常用於搜尋的列上面建立索引


PHP基礎

array_get() :將陣列以點形式連線

/**
 * Get an item from an array using "dot" notation.
 *
 * @param  \ArrayAccess|array  $array
 * @param  string  $key
 * @param  mixed   $default
 * @return mixed
 */
function array_get($array, $key, $default = null)
{
    return Arr::get($array, $key, $default);
}複製程式碼

array_uniqe() :陣列去重

/**
 * Removes duplicate values from an array
 * @link http://php.net/manual/en/function.array-unique.php
 * @param array $array <p>
 * The input array.
 * </p>
 * @param int $sort_flags [optional] <p>
 * The optional second parameter sort_flags
 * may be used to modify the sorting behavior using these values:
 * </p>
 * <p>
 * Sorting type flags:
 * SORT_REGULAR - compare items normally
 * (don't change types)
 * @return array the filtered array.
 * @since 4.0.1
 * @since 5.0
 */
function array_unique(array $array, $sort_flags = null) { }複製程式碼

date('Y-m-d', $timestamp):將時間戳轉換成日期格式

date('Y', $timestamp):獲取時間戳的年份,對應m【月份】,day【日期幾號】

$date = Carbon::parse('2018-10-05'):獲取一個對應日期的Carbon物件

$date->daysInMonth  這個月多少天

$date->startOfMonth(): 這個月第一天

$date->endOfMonth(): 這個月最後一天




相關文章