Laravel创建或更新相关模型

时间:2015-06-01 09:13:18

标签: php laravel laravel-5

我有以下功能来创建一个新的相关模型;

                //Create the results entry
                $result = new Result([
                    'result' => $total,
                    'user_id' => $user->id,
                ]);

                //attach it to the fixture - parse through looking for the user_id or opponent_id
                //to match the current user in the 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);

结尾处的 - > save()执行大部分魔术,将正确的fixture_id附加到结果表。问题是如果再次运行该函数,它会为相同的结果创建新条目。

有一个firstOrCreate()方法,但在保存相关模型时我不知道如何使用它。

由于

1 个答案:

答案 0 :(得分:0)

就像这样:http://laravel.com/docs/5.0/eloquent#insert-update-delete

//Create or find a 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 to $fixture's key)
 //any previous association will disappear. 
 $fixture->results()->associate($result);
 //save to write changes in the database.
 $result->save()

你可以在这里查看(https://github.com/laravel/framework/blob/5.0/src/Illuminate/Database/Eloquent/Model.php#L559)。 Laravel将在您的数据库中进行搜索并返回它是否找到它或创建一个新的。