简体   繁体   中英

90 Columns in a MySQL database table

I'm trying to find an optimal solution to my problem.

Basically I have a form that will consist of mostly checkboxes the form however the form will have some 60-90 checkboxes. And I will have a few of these forms so the problem I have is how to create this in most generic or simplistic way so I do not have to create each form for each table by hand.

My solution was to simply create a table the down side here is that I get a table with some 90 columns which is pretty messy to view in any client and has a little impact on performance as the table grows but not that much since most field types are tinyint.

In my Models I define a schema basically an array:

$schema = array(
  'column_name' => array('checkbox(input field type)', 'label')
);

public function getSchema()
{
 $this->schema['column_name]['value'] = $this->column_name;
 // .. Now I have to type this 100 times by hand..
}

This now allows me to just have 1 form and easily generate all the fields

    <form>
     @foreach($schema as $field => $attrs)
      @if($attrs[0] == 'checkbox')
       <input type="checkbox" name="{{ $field }}" value="{{ $attrs['value'] }} {{ ($attrs['value'] == 1) ? 'checked' : '' }}>{{ $attrs[1] }}
      @elseif($attrs[0] == 'text')
       ...
      @endif
     @endforeach

</form>

So it's a pretty elegant solution however I don't really gain that much if I have to define each field in getSchema() function for their value or that I must define schema array first which ends up being as if I defined two forms anyway.

I think I found somewhat solution here but don't fully know how to get rid of the manually defining the schema array and the method.

One of the ideas I had was to just have one field for value and define local variables in my model populate these when doing IO and serialize the object and store it but this seems wastefully and bad practice.

just create a new table with 4 columns

++++++++++++++++++++++++++++++++++++++++
id + entity_id + form_key + form_value
++++++++++++++++++++++++++++++++++++++++

This way all your values will be indexed and it's easier to manage.

checkbox -> 2 options = 1 bit.

one integer has 32 bits. one long integer has even more.

you can store your checkboxes into a bitmask. thus storing 100 checkboxes into 2-4 table columns. you can search, select, and update easily since mysql provides bit operations easily.

on the downside, any work with a database administration (eg phpmyadmin) and direct access to the database is brutal.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM