Created
April 3, 2012 03:25
-
-
Save jedateach/2289055 to your computer and use it in GitHub Desktop.
Planning new ShoppingCart system
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
* goal: build SQL filter, based on parameter array | |
*/ | |
//a hypothetical filter(parameters) for a new order item. | |
//This data would typically come from request parameters. | |
$filter = array( | |
'Size' => 20, | |
'Color' => 'blue', | |
'Premium' => true, | |
'Date' => '2-3-2014', | |
'RelatedObject' => 35 | |
); | |
//I could even introduce an extra callback to do more complex duplicate checks | |
//eg: date falls within a particular week, or size is between x and y | |
//this might come from OrderItem::$allowed_fields; | |
//this would prevent | |
$allowed_fields = array( | |
'Size', | |
'Color', | |
'Premium', | |
'Date' | |
); | |
foreach($filter as $key => $value){ | |
if(!in_array($key,$allowed_fields)){ | |
unset($filter[$key]); //remove non allowed fields | |
}else{ | |
$filter[$key] = Convert::raw2sql($value); | |
} | |
} | |
//TODO: automatically add in any other missing allowed fields as empty/null query | |
//otherwise you might get a result that you shouldn't | |
//eg a red sweater is not the same as a sweater | |
$filter['ProductID'] = $product->ID; | |
$filter['OrderID'] = $order->ID; | |
//add query to | |
$result = DataObject::get_one('OrderItem',$filter); |
I believe you can. See SQLQuery ->where function, which is the code DataObject::get uses for filtering.
EDIT: after things failing for a bit, I found it isn't / shouldn't be possible. ie, don't bother trying.
I think I may need ensure data is correctly formatted by passing each through appropriate DBField ->setValue. However, I can't see this happening in SearchContext, which is performing a similar role.
I've posted my updated (mostly working) idea here: https://gist.github.com/2395385
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
interesting concept. Can you pass an array to DataObject::get_one - is that possible or is this just shorthand?