2014-04-04 32 views
4

有了這個代碼:Laravel 4 - 型號不被保存

class SearchIndex extends Eloquent { 

    /** 
    * The database table used by the model. 
    * 
    * @var string 
    */ 
    protected $table = 'searchindex'; 

    //no timestamps 
    public $timestamps = false; 

    //mass-assignment 
    public $fillable = array('url', 'content', 'version', 'digest'); 
    public $guarded = array(); 

    public static function updateIndex($url, $version, $content) 
    { 
     self::retrieveSearchEntry($url, $version)->updateContent($content)->save(); 
    } 

    public static function retrieveSearchEntry($url, $version) 
    { 
     try 
     { 
      return self::withoutContent()->where('url', $url)->where('version', $version)->firstOrFail(array('url', 'version', 'digest')); 
     } 
     catch(\Illuminate\Database\Eloquent\ModelNotFoundException $e) 
     { 
      return new SearchIndex(array('url' => $url, 'version' => $version)); 
     } 
    } 

    public function updateContent($content) 
    { 
     $hash = md5($content); 
     if (!isset($this->digest) || ($this->digest != $hash)) 
     { 
      $this->content = $content; 
      $this->digest = $hash; 
     } 
     return $this; 
    } 

    public static function search($content) 
    { 

    } 
} 

如果我叫updateIndex提供URL +版本的新組合,被創建一個條目。
如果我打電話updateIndex提供現有的一對url +版本,條目不會更新新內容。我看到它與我忽略'內容'字段(原因:很大,我想設置它,而不是在那個函數中)有關。

問題:如何不能獲取內容字段,但可以在保存時設置它?

回答

2

已解決。原因:在firstOrFail()中執行自定義選擇時,我沒有選擇「id」字段。這樣,id爲空,生成的SQL試圖更新(因爲它是一個存在的對象)「where id爲NULL」,這會影響0行。