回答編集履歴

2

補足

2016/12/14 20:50

投稿

popobot
popobot

スコア6586

test CHANGED
@@ -7,3 +7,53 @@
7
7
  処理的にもパターン1は、戻り値とExceptionの両方を見ていて、問題ないと思います。
8
8
 
9
9
  モデルのinsert関数内でsave()の戻り値がfalseならExceptionを投げるほうがよりスマートかもしれませんけど
10
+
11
+
12
+
13
+ Controller
14
+
15
+ ```php
16
+
17
+ if ($this->request->is('post')) {
18
+
19
+ $this->Hoge->begin();
20
+
21
+ try {
22
+
23
+ $this->Hoge->insert($this->request->data);
24
+
25
+ $this->Fuga->insert($this->request->data);
26
+
27
+ $this->Hoge->commit();
28
+
29
+ $this->redirect('/');
30
+
31
+ } catch (Exception $e) {
32
+
33
+ $this->Hoge->rollback();
34
+
35
+ }
36
+
37
+ }
38
+
39
+ ```
40
+
41
+
42
+
43
+ Model
44
+
45
+ ```php
46
+
47
+ public function insert($data) {
48
+
49
+ $this->create();
50
+
51
+ if(!$this->save($data)) {
52
+
53
+ throw new InternalErrorException('error');
54
+
55
+ }
56
+
57
+ }
58
+
59
+ ```

1

補足

2016/12/14 20:50

投稿

popobot
popobot

スコア6586

test CHANGED
@@ -1,3 +1,9 @@
1
1
  複数のモデルそれぞれに保存するならパターン1のControllerでいいと思いますよ。
2
2
 
3
3
  なるべくモデル内でやりたいなら、Hogeモデル内のinsert関数内で、Fugaモデルのsaveも一緒にやってもいいと思います。
4
+
5
+
6
+
7
+ 処理的にもパターン1は、戻り値とExceptionの両方を見ていて、問題ないと思います。
8
+
9
+ モデルのinsert関数内でsave()の戻り値がfalseならExceptionを投げるほうがよりスマートかもしれませんけど