
detailsのテーブルを作る。
php artisan make:migration create_details_table
Schema::create('details', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('sub_category_id') ;
$table->string('detail_name', 50);
$table->timestamp('updated_at')->useCurrent()->nullable();
$table->timestamp('created_at')->useCurrent()->nullable();
});
php artisan migrate
モデムとコントローラを作る
php artisan make:model Detail
php artisan make:controller DetailController --resource
use App\Http\Controllers\DetailController;
Route::resource('details', DetailController::class);
コントローラーのjoin句。リレーション先の先の先まで参照。これできれいに動いた。
$details =Detail::select('details.id as detail_id' ,'categories.type_id','types.type_name','categories.category_number','categories.category_name','sub_categories.sub_category_number','sub_categories.sub_category_name','details.detail_name')
->join('sub_categories','details.sub_category_id',"=",'sub_categories.id')
->join('categories','sub_categories.category_id',"=",'categories.id')
->join('types','categories.type_id',"=",'types.id')
->orderBy('categories.type_id','asc')
->orderBy('categories.category_number','asc')
->orderBy('sub_categories.sub_category_number','asc')
->get();
javascriptでラジオボタンを押すとドロップダウンリストが変化する。
<script>
function setOption(radio) {
if ((radio.value) == '1') {
var listdata = JSON.parse('<?php echo json_encode($subcategoriesin)?>');
} else {
var listdata = JSON.parse('<?php echo json_encode($subcategoriesspend)?>');
}
const subcategorynumber = document.getElementById('sub_category_number');
// プルダウンをリセット
const options = document.querySelectorAll('#sub_category_number > option');
options.forEach(option => {
option.remove();
});
// プルダウンに「選択してください」を加える
const firstSelect = document.createElement('option');
firstSelect.textContent = '選択してください';
subcategorynumber.appendChild(firstSelect);
listdata.forEach(function( listdatavalue ) {
const option = document.createElement('option');
//select as でidの名称変更
option.value=listdatavalue.sub_category_id;
//join句のため,表記注意
option.textContent = listdatavalue.type_id+"/"+listdatavalue.category_number+"/"+listdatavalue.category_name+"/"+listdatavalue.sub_category_number+"/"+listdatavalue.sub_category_name ;
subcategorynumber.appendChild(option);
});
}
</script>
bladeでのラジオボタンとの設定
<div class="flex sm:items-center mb-6 flex-col sm:flex-row">
<label class="sm:w-1/3 font-bold sm:text-right mb-1 pr-4">収支区分<span class="text-red-500"> * </span></label>
<div class="w-full sm:w-2/3 bg-gray-200 py-2 px-3 text-gray-700">
<input type="radio" name="type_id" id="type_id_1" value="1" onchange="setOption(this);" @if ( old( 'type_id' ) == 1 )checked @endif>
<label class="text-lg mr-10" for="type_id_1">収入</label>
<input type="radio" name="type_id" id="type_id_2" value="2" onchange="setOption(this);" @if ( old( 'type_id' ) == 2 )checked @endif>
<label class="text-lg" for="type_id_2">支出</label>
</div>
</div>
ラジオボタンで支出を選ぶと、プルダウンは支出項目のみのリストを表示する。

コメント