在 Laravel 中查找或创建

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/52732726/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 18:06:22  来源:igfitidea点击:

findOrCreate in laravel

laravelcontrollereloquent

提问by Na Koriah

I want to create data but if the data already in database, it will update. but if the data not already in database, it will create new data.

我想创建数据,但如果数据已经在数据库中,它将更新。但如果数据不在数据库中,它将创建新数据。

this my controller

这是我的控制器

public function store(Request $request)
{      
    $real = SpentTime::findOrCreate([
        'plan_id' => $request->get ('plan_id'),
        'daily_spent_time' => $request->get ('daily_spent_time'),
        'daily_percentage' => $request->get ('daily_percentage'),
        'reason' => $request->get ('reason')
    ]);

    return redirect()->route('real.index', compact( 'reals'));
}

this my model

这是我的模型

public static function findOrCreate($plan_id)
{
    $real = SpentTime::find($plan_id);
    return $real ?: new SpentTime;
}

when I make data already in the database, the data is not updated.

当我在数据库中制作数据时,数据不会更新。

回答by Parth kharecha

Try like this

像这样尝试

$user = User::firstOrNew(array('name' => Input::get('name')));
$user->foo = Input::get('foo');
$user->save()

回答by Jignesh Joisar

try this one

试试这个

public function store(Request $request)
{      
    $real = SpentTime::findOrCreate($request->get('plan_id'),[
        'plan_id' => $request->get ('plan_id'),
        'daily_spent_time' => $request->get ('daily_spent_time'),
        'daily_percentage' => $request->get ('daily_percentage'),
        'reason' => $request->get ('reason')
    ]);

    return redirect()->route('real.index', compact( 'reals'));
}

public static function findOrCreate($plan_id,$data)
{
    $real = static::where('plan_id',$plan_id)->first();
    if (is_null($real)) {
        return static::create($data);
    } else {
        return $real->update($data);
    }
}