Laravelテスト機能完成
①やったこと
✖ $card_ids = array_column($cards, 'id');
〇 $card_ids = $cards->pluck('id');
の修正で上手くいってidカラムのみの配列はできたけど、
$card_ids =(array)$card_ids;
$card_id = array_rand ($card_ids, 1);
が0になってしまい失敗。やり方変える。
↓でやって成功!
public function test(Request $request, $id) {
$user = User::find($id);
$scope = $request->input('scope');
$style = $request->input('style');
$previous_card_id = $request->input('previous_card_id');
if ($scope == 'my_cards') {
$cards = $user->cards();
} else {
$cards = $user->good_cards();
}
$count_cards = $cards->count();
if($count_cards > 0) {
$card_ids = $cards->pluck('cards.id');//取得したカードたちのid全て取得
$max_key = $count_cards-1;
$card_id_key = random_int(0, $max_key);
$card_id = $card_ids[$card_id_key];
//カードが一枚の時に次の問題を変えないために
if ($previous_card_id != null && $count_cards != 1){
while ($card_id == $previous_card_id) {
$card_id_key = random_int(0, $max_key);
$card_id = $card_ids[$card_id_key];
}
}
$card = Card::find($card_id);
} else {
$card = null;
$card_id = null;
}
return view('test.test', [
'card' => $card,
'previous_card_id' => $card_id,
'scope' => $scope,
'style' => $style,
]);
}
②教訓
1.配列のキーは0から!!
配列の1番目をarray[1]で取り出そうとしないこと!→凡ミス
2.中間テーブル経由で取得する際はカラム名に注意。
カラム名だけだとあいまいになるからテーブル名も記載する。
$card_ids = $cards->pluck('cards.id');
③まとめ
1ページずつのpaginationの解決法が分からず、前に出た問題が出てしまう仕方なしの方法だけどひとまずテスト機能完成!
paginationでやって「絶対出ない問題がある」より良いだろうということで、
当面これ採用します。