php - Laravel Create OR update related model -
i have following function create new related model;
//create results entry $result = new result([ 'result' => $total, 'user_id' => $user->id, ]); //attach fixture - parse through looking user_id or opponent_id //to match current user in loop. $fixture = leaguefixture::where('league_id', $league_id) ->where('gameweek', $gameweek) ->where(function($q) use ($user){ $q->where('user_id', $user->id) ->orwhere('opponent_id', $user->id); }) ->first(); $fixture->results()->save($result);
the ->save() @ end of magic, attaching correct fixture_id result table. problem if function run again, creates new entries same results.
there firstorcreate() method, don't know how use when saving related model.
thanks
it's this: http://laravel.com/docs/5.0/eloquent#insert-update-delete.
//create or find existing one... $result = result::firstorcreate([ 'result' => $total, 'user_id' => $user->id, ]); //grab fixture... $fixture = leaguefixture::where('league_id', $league_id) ->where('gameweek', $gameweek) ->where(function($q) use ($user){ $q->where('user_id', $user->id) ->orwhere('opponent_id', $user->id); }) ->first(); //associate (set fixture_id in $result equals $fixture's key) //any previous association disappear. $fixture->results()->associate($result); //save write changes in database. $result->save()
you can check here (https://github.com/laravel/framework/blob/5.0/src/illuminate/database/eloquent/model.php#l559). laravel search in database , return if found or create new.
Comments
Post a Comment