我想创建数据,但是如果数据已经存在于数据库中,它将进行更新。但是,如果数据尚未存储在数据库中,它将创建新数据。
这是我的控制器
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'));
}
这是我的模特
public static function findOrCreate($plan_id)
{
$real = SpentTime::find($plan_id);
return $real ?: new SpentTime;
}
当我已经在数据库中创建数据时,数据不会更新。
答案 0 :(得分:2)
尝试这样
$user = User::firstOrNew(array('name' => Input::get('name')));
$user->foo = Input::get('foo');
$user->save()
答案 1 :(得分:1)
尝试这个
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);
}
}