鍍金池/ 問答/PHP/ 為什么laravel默認(rèn)將空字符串轉(zhuǎn)換為null呢

為什么laravel默認(rèn)將空字符串轉(zhuǎn)換為null呢

    1. laravel 全局中間件下ConvertEmptyStringsToNull這個中間件,默認(rèn)把空字符串轉(zhuǎn)換為null,但是空字符串不是比null的效率要好么?
    2. 我數(shù)據(jù)庫字段設(shè)置為not null, 并且設(shè)置默認(rèn)值為,檔表單傳上來的時候如果沒有值會被中間件轉(zhuǎn)為null,每次都要注釋掉這個中間件,誰能講下轉(zhuǎn)為null到底為什么?哪里好?
    1. 追加一個圖來描述

    clipboard.png

    回答
    編輯回答
    寫榮

    問題1:
    官方?jīng)]有任何文獻(xiàn)說明 空字符串null 效率高。

    問題2:
    數(shù)據(jù)庫設(shè)計是矛盾的,既然默認(rèn)值是,就沒必要設(shè)置字段為 not null。如果你非要這樣,你可以在 controller 里面使用 array_filter($request->all()) 來過濾掉 null 或者 空字符串 的參數(shù)。

    最后,Laravel 是在 5.4 開始加入的,同時加入的還有 TrimStrings, 官方的提交記錄沒有說明是為了什么,個人認(rèn)為官方是為了標(biāo)準(zhǔn)化數(shù)據(jù)格式,進(jìn)行統(tǒng)一規(guī)范。

    =======分割線=======

    繼續(xù)補(bǔ)充一下:

    如果非要按照自己的要求來,也建議不要直接去注釋掉官方的中間件引用,以免其他問題,可以定義你自己的 request,在request 處理這個參數(shù)的時候,修改成自己想要的值。

    php artisan make:request YourRequest

    =======繼續(xù)割========

    By default, Laravel includes the TrimStrings and ConvertEmptyStringsToNull middleware in your application's global middleware stack. These middleware are listed in the stack by the AppHttpKernel class. These middleware will automatically trim all incoming string fields on the request, as well as convert any empty string fields to null. This allows you to not have to worry about these normalization concerns in your routes and controllers.

    If you would like to disable this behavior, you may remove the two middleware from your application's middleware stack by removing them from the $middleware property of your AppHttpKernel class.

    看官方描述的意思 TrimStringsConvertEmptyStringsToNull 就是為了規(guī)范化數(shù)據(jù)。

    2018年3月31日 14:41