terrific
terrific

Reputation: 1667

How to map enum with the string or viceversa in order to save into database?

I have in my database a coloumn say agent which can have enum values ('G','Y','M') where G= google Y= yahoo M= msn

how should i map the output coming from my function i.e google as G in my code so that database recognise it and saves it??

Upvotes: 0

Views: 6922

Answers (3)

mark
mark

Reputation: 21743

Since Cake does not support enums, you might want to use tinyint(2) fields and this approach: http://www.dereuromark.de/2010/06/24/static-enums-or-semihardcoded-attributes/

It is faster, easier to maintain and also works with your (custom) bake templates.

Upvotes: 0

Travis Leleu
Travis Leleu

Reputation: 4240

You're already using ENUM data types, which are just an integer. Why not (in your DB schema, where you define ENUM), just define ENUM('Google','Yahoo','MSN', ...)? That's what I do -- then, when you're pulling/pushing data, you can just use the literal enum value (PHP will treat it like a string when you grab data from the db, and MySQL will treat the string passed from PHP as the enum type, assuming it's the same).

There's really no reason to use 'G' over 'Google', unless you're really that lazy of a typist. And if you're that lazy, why would you want to put another layer of indirection into your code, unnecessarily?

Edit: Sorry for the tone of the post -- it came off as far more harsh than intended. I just happen to feel pretty strongly against unnecessary indirection.

Upvotes: 1

artur02
artur02

Reputation: 4479

I think the easiest way is to get the int representation of the enum value. Enums are numbers in the background, so it's usually easy to cast an enum member to a number and vice versa.

You can write a converter class for the best flexibility. You can process the enum value and generate a string, or get a string and return an enum member. You can do this in a simple if-then-else or switch-case structure.

If you are using .NET (C#), be aware that you can pass any number as a parameter even you specify an enum, so an else or a default branch is a must in case of conversion.

If you are using PHP, here is an example:

 $myEnum = array ("red" => 1,"blue" => 2,"yellow" => 3); 
 $d = $myEnum["red"];

You will get 1 for red, 3 for yellow. If you want to use a string:

$myEnum = array ("Google" => "G","Yahoo" => "Y","MSN" => "M"); 
$d = $myEnum["Google"];

Upvotes: 4

Related Questions