2013-08-28 106 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 
}