2015-10-05 96 views
13

我想在我的表中存儲整數數組,我找不到任何支持數組的類型Documentation,任何建議。Laravel遷移陣列類型

遷移:

public function up() 
{ 
    Schema::create('pickups', function (Blueprint $table) { 
     $table->increment('id'); 
     $table->boolean('default'); 
     $table->integer('shifts'); <<--------- HERE I want to store an array of integers 
     $table->integer('status_id'); 

     $table->timestamps(); 
    }); 
} 

回答

24

array數據類型是不存在於所有的數據庫系統,並且由於Laravel的架構構建的數據庫無關,它不提供方法來創建非普通數據類型的列。所以你有兩個選擇:

1.使用原始的SQL語句來添加列,就像我認爲應該工作的語句。通過使用attribute casting

DB::statement('ALTER TABLE pickups ADD COLUMN shifts integer[]'); 

2.用雄辯的可用的解決方法:雖然我不知道,如果查詢生成器或機鋒能正確處理這些類型的列。在您的遷移創建列json像這樣:

public function up() 
{ 
    Schema::create('pickups', function (Blueprint $table) { 
     $table->increment('id'); 
     $table->boolean('default'); 
     $table->json('shifts'); 
     $table->integer('status_id'); 

     $table->timestamps(); 
    }); 
} 

然後你可以設置你的Pickup模型(如果你還沒有這樣做的話),並使用$casts屬性:

class Pickup extends Model 
{ 
    protected $casts = [ 
     'shifts' => 'array' 
    ]; 
} 

這將讓Eloquent知道當它從數據庫中提取數據時,它必須將shifts列值轉換爲array。這只是模擬實際的數組,因爲在數據庫級別,該列的類型爲TEXT,並且該數組已被序列化。但是,在反序列化列值時,Eloquent會返回一個實際的整數數組供您在代碼中使用。下面是一個例子用例:

// Create a new Pickup entry 
$pickup = App\Pickup::create([ 
    'default' => true, 
    'shifts' => '[1, 5, 7]', // you can easily assign an actual integer array here 
    'status_id' => 1 
]); 

假設與id等於1上述生成的條目時,在以後檢索的條目:

$pickup = App\Pickup::find(1); 
dump($pickup->shifts); 

dump()從上面的代碼將輸出一個實際的數組整數:

array:3 [▼ 
    0 => 1 
    1 => 5 
    2 => 7 
] 
+0

謝謝@Bogdan爲您的答案,不幸的是,當我嘗試創建新的皮卡條目與''班'=> [1,5 ,7],'我收到這個錯誤信息'PHP警告:preg_replace():參數不匹配,模式是字符串,而替換是數組'。 –

+0

好吧現在它的工作方式就像''shift'=>'[1,5,7]',',謝謝:) –

+0

我已經測試了這個乾淨的安裝Laravel 5.1,對我來說它實際上沒有放置引號在分配值時在數組周圍。 – Bogdan