2016-05-01 181 views
0

我正在使用PHP和laravel框架創建一個Web應用程序。我的代碼中有以下類。使用PHP和laravel框架在MySql數據庫中存儲對象數組

class ReportField extends Model 
{ 
    // 
    public $name; 
    public $quantity; 
    public $unitCost; 
    public $totalCost; 
    public $estimation; 
} 

我使用序列化將這些對象的數組寫入數據庫。

$fieldsList=array(); 
foreach($items as $item){ 
     if($item->sale_type == 1){ 

       $reportField=new ReportField(); 
       $reportField->name=$item->item_name; 
       $reportField->unitCost=$item->unit_cost; 
       array_push($fieldsList,serialize($reportField)); 
     } 
} 

$gpForecast=new GPForecast(); 
$gpForecast->project_id=$project_id; 
$gpForecast->fieldList=(serialize($fieldsList)); 
$gpForecast->save(); 

現在反序列化之後,我想將數組中的那些對象轉換回RecordField對象。

$gpForecast=GPForecast::all()->first(); //here i read one of array i write to database 
$fieldList=unserialize($gpForecast->fieldList); 
foreach($fieldList as $field){ 
     echo $field->name; 
} 

但後來我得到錯誤Trying to get property of non-object那麼我該如何糾正這個問題?

+0

難道你不應該爲你的模型屬性使用'protected $ fillable'嗎? – haakym

回答

1

這個:array_push($fieldsList,serialize($reportField)我覺得如果你在做迭代後做$gpForecast->fieldList=(serialize($fieldsList)); 沒用。這也可能導致大公你得到空項 - 在這裏:

foreach($fieldList as $field){

你試圖去序列化的數據

(在這裏你它們序列:array_push($fieldsList,serialize($reportField));)。

這意味着你不會得到ReportField對象,但可能序列化數據。

相關問題