Laravel如何只在它的新插入时增加?

时间:2018-02-09 11:35:08

标签: php mysql laravel

每次添加新产品时,我都需要在Categories表中增加'total_products'字段。但是,当现有产品更新时,我不希望它增加。我现在正在这样做:

Category::findOrNew($product->cat_id)->increment('total_products',1);

但是此代码无法识别它是更新还是新插入。无论插入或更新,它都会增加'total_products'。如何在新插入时使其增量?

2 个答案:

答案 0 :(得分:1)

显然是两个查询,每个单独的查询尝试

$cat = Category::find($product->cat_id);
if($cat){
    $cat->increment('total_products',1);
}else{
    $cat = new Category();
    $cat->total_products = 1;
    // Inert new category here with all related data
    $cat->save(); 
}
return $cat->id;

还要确定何时增加total_productsafter insertafter update

答案 1 :(得分:0)

使用firstOrCreate方法:

$category = Category::firstOrCreate(['name' => 'John Doe']);

如果您想知道用户是创建还是获取,请检查wasRecentlyCreated属性:

if ($category->wasRecentlyCreated) {
    // "firstOrCreate" didn't find the user in the DB, so it created it.
} else {
    // "firstOrCreate" found the user in the DB and fetched it.
}