回答編集履歴

1

2015/02/06 02:57

投稿

gardeningojisan
gardeningojisan

スコア28

test CHANGED
@@ -1,47 +1,20 @@
1
1
  LaravelだとfindOrFail()はあるんですが
2
-
3
- [http://laravel4.kore1server.com/docs/eloquent#introduction](http://laravel4.kore1server.com/docs/eloquent#introduction)
2
+ http://laravel4.kore1server.com/docs/eloquent#introduction
4
-
5
3
  FindOrCreate()はないですね・・・。
6
-
7
4
  ですので自作する必要があります。
8
-
9
-
10
5
 
11
6
  下記のようなクエリースコープをモデルに追加します。
12
7
 
13
8
 
14
-
15
-
16
-
17
- ```lang-<ここに言語を入力>
18
-
19
- public function scopeFindOrCreate($q, $id) {
9
+ public function scopeFindOrCreate($q, $id) {
20
-
21
- $obj = $q->find($id);
10
+ $obj = $q->find($id);
22
-
23
- return $obj ?: new static;
11
+ return $obj ?: new static;
24
-
25
12
  }
26
-
27
- ```
28
-
29
-
30
13
 
31
14
  使うときは以下のようにします。
32
15
 
33
-
34
-
35
- ```lang-<ここに言語を入力>
36
-
37
16
  $item = Item::findOrCreate($id);
38
-
39
17
  $item->id = $id;
40
-
41
18
  $item->name = 'hoge';
42
-
43
19
  $item->save();
44
20
 
45
- ```
46
-
47
-