Escolar Documentos
Profissional Documentos
Cultura Documentos
6 / / DivingintoPrestaShopCoreDevelopment
Accessingthedatabase
CreadoporXavierBorderie,modificadoporltimavezenmay05,2014
Accessingthedatabase
Thedatabasestructure
Bydefault,PrestaShop'sdatabasetablesstartwiththeps_prefix.Thiscanbecustomizedduringinstallation
Alltablenamesareinlowercase,andwordsareseparatedwithanunderscorecharacter("_"):
ps_employee
ps_manufacturer
ps_product
ps_product_comment
ps_shop_url
Whenatableestablishesthelinksbetweentwoentities,thenamesofbothentitiesarementionedinthetable'sname.Forinstance,
ps_category_productlinksproductstotheircategory.
Afewdetailstonoteabouttables:
Tableswhichcontaintranslationsmustendwiththe_langsuffix.Forinstance,ps_product_langcontainsallthetranslations
fortheps_producttable.
Tableswhichcontaintherecordslinkingtoaspecificshopmustendwiththe_shopsuffix.Forinstance,ps_category_shop
containsthepositionofeachcategorydependingonthestore.
Thereisalsoacoupleofstandardpracticesfordatarowswithinatable:
Usetheid_langfieldtostorethelanguageassociatedwitharecord.
Usetheid_shopfieldtostorethestoreassociatedwitharecord.
TheDBQueryclass
TheDBQueryclassisaquerybuilderwhichhelpsyoucreateSQLqueries.Forinstance:
$sql=newDbQuery();
$sql>select('*');
$sql>from('cms','c');
$sql>innerJoin('cms_lang','l','c.id_cms=l.id_cmsANDl.id_lang='.(int)$id_lang);
$sql>where('c.active=1');
$sql>orderBy('position');
returnDb::getInstance()>executeS($sql);
Herearesomeofthemethodsfromthisclass:
Methodnameandparameters
Description
__toString()
Generateandgetthequery.
build()
Generateandgetthequery(returnastring).
from(string$table,mixed$alias=null)
SettableforFROMclause.
groupBy(string$fields)
AddaGROUPBYrestriction.
having(string$restriction)
AddarestrictionintheHAVINGclause(eachrestrictionwillbeseparatedby
anANDstatement).
innerJoin(string$table,string$alias=null,string
$on=null)
AddaINNERJOINclause,E.g.$this>innerJoin('productpON...').
join(string$join)
AddaJOINclause,E.g.$this>join('RIGHTJOIN'._DB_PREFIX_.'productp
ON...').
leftJoin(string$table,string$alias=null,string
$on=null)
AddaLEFTJOINclause.
leftOuterJoin(string$table,string$alias=null,
string$on=null)
AddaLEFTOUTERJOINclause.
limit(string$limit,mixed$offset=0)
Limitresultsinquery.
naturalJoin(string$table,string$alias=null)
AddaNATURALJOINclause.
orderBy(string$fields)
AddanORDERBrestriction.
select(string$fields)
Addfieldsinqueryselection.
where(string$restriction)
AddarestrictioninWHEREclause(eachrestrictionwillbeseparatedbyan
ANDstatement).
TheObjectModelclass
Whenneedingtodivedeep,youhavetousetheObjectModelclass.ThisisthemainobjectofPrestaShop'sobjectmodel.Itcanbe
overridden...withprecaution.
ItisanActiveRecordkindofclass(see:http://en.wikipedia.org/wiki/Active_record_pattern).Thetableattributesorviewattributesof
PrestaShop'sdatabaseareencapsulatedinthisclass.Therefore,theclassistiedtoadatabaserecord.Aftertheobjecthasbeen
instantiated,anewrecordisaddedtothedatabase.Eachobjectretrievesitsdatafromthedatabasewhenanobjectisupdated,the
recordtowhichitistiedisupdatedaswell.Theclassimplementsaccessorsforeachattribute.
Definingthemodel
Youmustusethe$definitionstaticvariableinordertodefinethemodel.
Forinstance:
/**
*ExamplefromtheCMSmodel(CMSCore)
*/
publicstatic$definition=array(
'table'=>'cms',
'primary'=>'id_cms',
'multilang'=>true,
'fields'=>array(
'id_cms_category'=>array('type'=>self::TYPE_INT,'validate'=>'isUnsignedInt'),
'position'=>array('type'=>self::TYPE_INT),
'active'=>array('type'=>self::TYPE_BOOL),
//Languagefields
'meta_description'=>
array('type'=>self::TYPE_STRING,'lang'=>true,'validate'=>'isGenericName','size'=>255
'meta_keywords'=>
array('type'=>self::TYPE_STRING,'lang'=>true,'validate'=>'isGenericName','size'=>255
'meta_title'=>
array('type'=>self::TYPE_STRING,'lang'=>true,'validate'=>'isGenericName','required'=>
'link_rewrite'=>
array('type'=>self::TYPE_STRING,'lang'=>true,'validate'=>'isLinkRewrite','required'=>
'content'=>
array('type'=>self::TYPE_HTML,'lang'=>true,'validate'=>'isString','size'=>3999999999999
),
);
Amodelformanystoresand/orlanguages
Inordertoretrieveanobjectinmanylanguages:
'multilang'=>true
Inordertoretrieveanobjectdependingonthecurrentstore
'multishop'=>true
Inordertoretrieveanobjectwhichdependsonthecurrentstore,andinmanylanguages:
'multilang_shop'=>true
Themainmethods
AnyoverridingoftheObjectModelmethodsisboundtoinfluencehowalltheotherclassesandmethodsact.Usewithcare.
Methodnameandparameters
Description
__construct($id=NULL,$id_lang=NULL)
Buildobject.
add($autodate=true,$nullValues=false)
Savecurrentobjecttodatabase(addorupdate).
associateTo(integer|array$id_shops)
Associateanitemtoitscontext.
delete()
Deletecurrentobjectfromdatabase.
deleteImage(mixed$force_delete=false)
Deleteimagesassociatedwiththeobject.
deleteSelection($selection)
Deleteseveralobjectsfromdatabase.
getFields()
PreparefieldsforObjectModelclass(add,update).
getValidationRules($className=_CLASS_)
Returnobjectvalidationrules(fieldvalidity).
save($nullValues=false,$autodate=true)
Savecurrentobjecttodatabase(addorupdate).
toggleStatus()
Toggleobject'sstatusindatabase.
update($nullValues=false)
Updatecurrentobjecttodatabase.
validateFields($die=true,$errorReturn=false)
Checkforfieldvaliditybeforedatabaseinteraction.