如果存在:更新,否则:在Laravel 5.5中插入

时间:2018-08-31 17:33:30

标签: php laravel laravel-5.5

我试图弄清楚控制器中的if if是否正确。它可以工作,不会产生错误,但是更新不起作用。即使它存在,它仍然会添加一个新的

public function store(Request $request)
{

    $collection = Collection::create([
        'assignment_id' => $request->input('assignment_id'),
        'bag_id' => $request->input('bag_id'),
        'weight' => $request->input('weight')
    ]);


    $station = Collection::join('assignments', 'collections.assignment_id', '=', 'assignments.id')
        ->join('stations', 'assignments.station_id', '=', 'stations.id')
        ->select('stations.id')
        ->where('collections.id', '=', $collection->id)
        ->first();

    $weight = Collection::join('assignments', 'collections.assignment_id', '=', 'assignments.id')
        ->join('stations', 'assignments.station_id', '=', 'stations.id')
        ->select('collections.weight')
        ->where('collections.id', '=', $collection->id)
        ->first();

    //query in selectings process that exists within a month
    $processexist = Process::select('*')
        ->where('bag_id', $request->input('bag_id'))
        ->whereMonth('created_at', date('m'))
        ->first();

    if($processexist == null)//if doesn't exist: create
    {
        $processes = Process::create([
            'bag_id' => $request->input('bag_id'),
            'station_id' => $station->id,
            'total_weight' => $weight->weight
        ]); 
    }
    else //if exist: update
    {
        $processes = Process::where('id', $processexist->id)
            ->update(['weight'=>sum($weight->weight)]);
    }

    return redirect('/collections');
}

在我的CollectionsController商店中,每次添加集合时,都会添加一个过程。如果该过程存在,则只会更新权重,而不会,它将添加新的权重。就像我说的那样,如果存在,它不会更新,但是会更新。希望您能帮我弄清楚。谢谢!

2 个答案:

答案 0 :(得分:1)

如果想求和,就不能尝试

 $processes = Process::where('id', $processexist->id)->first();
 $processes->weight += $weight->weight;
 $processes->save();

答案 1 :(得分:1)

如果存在将返回它,否则创建一个(已经保存在数据库中)

$process = Process::findOrCreate(array $attributes, array $values = []);

如果存在将返回它,否则将实例化一个新的(不会保存在数据库中);

$process = Process::findOrNew(array $attributes, array $values = []);

还有

Process::updateOrCreate(array $attributes, array $values = [])

https://laravel.com/api/5.5/Illuminate/Database/Eloquent/Builder.html#method_findOrNew