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

Php 如果存在:更新,否则:在Laravel 5.5中插入,php,laravel,laravel-5.5,Php,Laravel,Laravel 5.5,我想弄清楚控制器中的if-else是否正确。它可以工作,不会产生错误,但更新不起作用。即使它存在,它仍然会添加一个新的 public function store(Request $request) { $collection = Collection::create([ 'assignment_id' => $request->input('assignment_id'), 'bag_id' => $request->input

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

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中的存储中,每次添加集合时,都会添加一个进程。如果这个过程存在,它只会更新权重,但不会,它会添加一个新的权重。就像我说的,如果它存在,它不会更新,但它会是一个新的。我希望你能帮我弄明白。谢谢

如果你想求和,就不能尝试

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

如果你想求和,你就不能尝试这个

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

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


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


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


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


你把
求和
这个应用到数组你返回一个
对象
你把
求和
这个应用到数组你返回一个
对象
$process = Process::findOrNew(array $attributes, array $values = []);
Process::updateOrCreate(array $attributes, array $values = [])