Laravelのクエリビルダで該当するレコードを取得するにあたり、下記のようなコードを書きました。
Controllerで該当レコードの有無を判別し、該当が無い場合は例外処理するよう考えております。
質問は、Controllerでの条件分岐の方法についてです。
php
1 /** 2 * Get profiles by user id. 3 * 4 * @param $id int 5 * @return Illuminate\Database\Eloquent 6 */ 7 public function getprofilesById($id) 8 { 9 $profile = $this->profile 10 ->where('user_id', $id) 11 ->orderBy('profiles.id', 'ASC') 12 ->select('name', profiles.id') 13 ->get(); 14 15 return $profile; 16 }
現在のControllerは下記です。
多くのサンプルコードを見ると、下記if条件の**(count($profiles) <= 0)の部分を(empty($profiles))**としてあります。私の場合これではできませんでした。どのような理由でしょうか?
DBからのデータの取得の方法が間違っているのか、controllerの中の記述に誤りがあるのか原因を知りたいです。
php
1 /** 2 * Display the specified resource. 3 * 4 * @param int $user_id 5 * @return \Illuminate\Http\Response 6 */ 7 public function show($user_id) 8 { 9 $profiles = $this->Service->getprofilesById($user_id); 10 //該当が無い場合 11 if (count($profiles) <= 0) { 12 return $this->Service->getAllUsersprofiles(); 13 } 14 //該当がある場合 15 return $this->responseOk($profiles); 16 }
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/05/31 09:56