2013-08-28 51 views
29

我最近開始使用雄辯。如何檢查記錄是否是Laravel中的新記錄?

當我使用PHP Active Record時,有一個很好的函數檢查記錄是從數據庫加載還是一個新實例。在我能使用的雄辯中有沒有類似的東西?

通過新我的意思是:

$article = new Article; 

,而一個從數據庫將

$article = Article::find(1); 

回答

81

所有laravel車型有->exists屬性。

更具體地說,如果該模型要麼從數據庫加載,要麼自從創建後已保存到數據庫,exists屬性將爲true;否則它將是錯誤的。

如果您想知道模型是從數據庫中抓取還是根本不保存(也就是說如果需要保存),那麼您可以使用->isDirty()函數。

對於這類信息,Laravel API是一個有用的地方: http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Model.html#method_isDirty 並且通常比默認文檔更流暢。

+33

不幸的是,Laravel的文檔幾乎沒有劃傷的框架表面。 –

+12

不要與方法'$ model-> exists()'混淆,它會執行其他操作,例如計算數據庫中的行數,並在count> 0時返回:) –

-3
$article = new Article; 
var_dump($article->id); == null 

$article = Article::find(1); 
var_dump($article->id); == string(1) "1" 

所以

if ($article->id) { 
    // I am existing 
} else { 
    // I am new 
} 
0

我使用Laravel Eloquent的updateOrCreate()方法來創建或更新從CSV文件導入時的記錄。

$product = $this->updateOrCreate($attributes, $values); 

我想統計新創建的記錄和更新記錄的數量。由於updateOrCreate()方法在創建時將記錄保存到數據庫,$product->exists將始終返回true

另一種方法是模型的created_atupdated_at時間戳與當前時間比較:

if($product->created_at == Carbon::now()) 
      $created++; 
     elseif ($product->updated_at == Carbon::now()) 
      $updated++; 
1

我們可以在模型中使用$appends,如果你會用很多次。例如,以檢查新創建的評論在創建後進行編輯。

class Comment extends Model 
{ 
    protected $appends = ['is_edited']; 

    public function getIsEditedAttribute() 
    { 
      return $this->attributes['is_edited'] = ($this->created_at != $this->updated_at) ? true : false; 
    } 
} 

您可以使用它像

$comment = Comment::findOrFail(1); 

if($comment->is_edited){ 
     // write your logic here 
} 
10

你的模型對象只有專爲一個屬性。這是最近創建:

$item = Item::firstOrCreate(['title' => 'Example Item']); 

if ($item->wasRecentlyCreated === true) { 
    // item wasn't found and have been created in the database 
} else { 
    // item was found and returned from the database 
}