回答編集履歴

3

scopeOfのOfは不要だったため削除

2017/11/22 01:33

投稿

masaya_ohashi
masaya_ohashi

スコア9206

test CHANGED
@@ -36,7 +36,7 @@
36
36
 
37
37
 
38
38
 
39
- public function scopeOfOrderByMyPrice($query) {
39
+ public function scopeOrderByMyPrice($query) {
40
40
 
41
41
  return $query->orderBy($this->myPriceColumnName(), 'asc'); // scope処理でorderByを付ける
42
42
 
@@ -104,7 +104,7 @@
104
104
 
105
105
 
106
106
 
107
- public function scopeOfOrderByMyPrice($query) {
107
+ public function scopeOrderByMyPrice($query) {
108
108
 
109
109
  if (\Auth::User()->role == 'admin') {
110
110
 

2

Ofが抜けていたので修正

2017/11/22 01:33

投稿

masaya_ohashi
masaya_ohashi

スコア9206

test CHANGED
@@ -104,7 +104,7 @@
104
104
 
105
105
 
106
106
 
107
- public function scopeOrderByMyPrice($query) {
107
+ public function scopeOfOrderByMyPrice($query) {
108
108
 
109
109
  if (\Auth::User()->role == 'admin') {
110
110
 

1

仕様変更後

2017/11/20 09:47

投稿

masaya_ohashi
masaya_ohashi

スコア9206

test CHANGED
@@ -57,3 +57,93 @@
57
57
  ->paginate(20);
58
58
 
59
59
  ```
60
+
61
+
62
+
63
+ ### 仕様変更後
64
+
65
+ 正直仕様が複雑すぎて、PHP側の処理とSQL側の処理を共通化して書くとか無理です…同じ動作をするように力技でSQLを書くしかないかと思います。
66
+
67
+
68
+
69
+ 全然動作確認してないので、このまま正しく動くかどうかはわかりませんが…joinとかDB::rawのサブクエリを使えばどうにかできるかと思います。
70
+
71
+ ```PHP
72
+
73
+ class Item extends Model
74
+
75
+ {
76
+
77
+ public function myPrice () {
78
+
79
+ if (\Auth::User()->role == 'admin') {
80
+
81
+ $result = $this->master_price;
82
+
83
+ } else {
84
+
85
+ $data = $this->prices()->where('user_id', \Auth::User()->id)->first();
86
+
87
+ $result = (is_null($data) ? $this->master_price : $data->price);
88
+
89
+ }
90
+
91
+ return $result;
92
+
93
+ }
94
+
95
+
96
+
97
+ public function prices()
98
+
99
+ {
100
+
101
+ return $this->hasMany(Price::class);
102
+
103
+ }
104
+
105
+
106
+
107
+ public function scopeOrderByMyPrice($query) {
108
+
109
+ if (\Auth::User()->role == 'admin') {
110
+
111
+ $query
112
+
113
+ ->select(
114
+
115
+ 'items.*', // itemsテーブルのカラム全てと
116
+
117
+ 'items.master_price AS my_price' // master_priceをmy_priceとして追加
118
+
119
+ );
120
+
121
+ }
122
+
123
+ else {
124
+
125
+ $query
126
+
127
+ ->join(\DB::raw('(SELECT item_id, price FROM prices WHERE user_id = :user_id) AS prices', ['user_id' => \Auth::User()->id]), 'prices.item_id', 'items.id') // pricesからuser_idの一致するレコードを引き出し、itemsのidと紐付ける
128
+
129
+ ->groupBy('prices.item_id') // pricesのitem_idでグルーピングすることでpricesの結合を1件に絞り込む
130
+
131
+ ->select(
132
+
133
+ 'items.*', // itemsテーブルのカラム全てと
134
+
135
+ 'COALESCE(prices.price, items.master_price) AS my_price' // joinしたpricesのpriceがあればpriceを、なければmaster_priceをmy_priceとして追加
136
+
137
+ );
138
+
139
+ }
140
+
141
+ return $query->orderBy('my_price', 'asc'); // my_price順でソート
142
+
143
+ }
144
+
145
+ }
146
+
147
+ ```
148
+
149
+ 使い方は仕様変更前と同じです。Model内の実装だけが変わります。