【问题标题】:If exists: update, else: insert in Laravel 5.5 [duplicate]如果存在:更新,否则:插入 Laravel 5.5 [重复]
【发布时间】:2019-02-06 18:34:56
【问题描述】:

我试图弄清楚我的控制器中的 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 中,每次我添加一个集合时,都会添加一个进程。如果进程存在,它只会更新权重,但不会,它会添加一个新的。就像我说的,如果它存在,它不会更新,但它会是一个新的。我希望你能帮我弄清楚。谢谢!

【问题讨论】:

  • 你把sum这个应用于数组你返回一个object

标签: php laravel laravel-5.5


【解决方案1】:

如果存在则返回,否则创建一个(已保存在 DB)

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

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

$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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2015-07-04
      • 2013-04-19
      • 2014-11-29
      • 2011-04-30
      • 1970-01-01
      • 1970-01-01
      • 2019-10-17
      • 2012-12-13
      • 1970-01-01
      相关资源
      最近更新 更多