Joining Customer on Attribute - php

I'm trying to filter my orders which are returned back by the magento API by a customer attribute. I tried several approaches but nothing seem to work.
I'm using Magento 1.4.1.1 atm and the api does this at the moment:
$billingAliasName = 'billing_o_a';
$shippingAliasName = 'shipping_o_a';
$collection = Mage::getModel("sales/order")->getCollection()
->addAttributeToSelect('*')
->addAddressFields()
->addExpressionFieldToSelect(
'billing_firstname', "{{billing_firstname}}", array('billing_firstname'=>"$billingAliasName.firstname")
)
->addExpressionFieldToSelect(
'billing_lastname', "{{billing_lastname}}", array('billing_lastname'=>"$billingAliasName.lastname")
)
->addExpressionFieldToSelect(
'shipping_firstname', "{{shipping_firstname}}", array('shipping_firstname'=>"$shippingAliasName.firstname")
)
->addExpressionFieldToSelect(
'shipping_lastname', "{{shipping_lastname}}", array('shipping_lastname'=>"$shippingAliasName.lastname")
)
->addExpressionFieldToSelect(
'billing_name',
"CONCAT({{billing_firstname}}, ' ', {{billing_lastname}})",
array('billing_firstname'=>"$billingAliasName.firstname", 'billing_lastname'=>"$billingAliasName.lastname")
)
->addExpressionFieldToSelect(
'shipping_name',
'CONCAT({{shipping_firstname}}, " ", {{shipping_lastname}})',
array('shipping_firstname'=>"$shippingAliasName.firstname", 'shipping_lastname'=>"$shippingAliasName.lastname")
);
Which is the default API call I guess. Now I just want to join a customer attribute called update - how do I achieve this simple task?
Or is this not possible on a flat table like sales_flat_order?

Whenever I need to do this I use something like:
Joining An EAV Table (With Attributes) To A Flat Table
It's not well optimised but you should be able to pick out the parts you need.
PS.
I think I'll explain what I mean by optimised since it's important. In the heart of the method is this bit:
->joinLeft(array($alias => $table),
'main_table.'.$mainTableForeignKey.' = '.$alias.'.entity_id and '.$alias.'.attribute_id = '.$attribute->getAttributeId(),
array($attribute->getAttributeCode() => $field)
);
If you know MySQL then you'll know it will only pick one index when joining a table, the more specific the better. In this case only the entity_id and attribute_id fields are being used so MySQL is restricted to those. Both columns are indexed but the cardinality is low.
If the condition also included the entity type then MySQL would have the choice of using IDX_BASE which indexes the columns entity_type_id,entity_id,attribute_id,store_id in that order (it needs to process them left to right). So something like this results in a much improved EAV performance - depending on how many rows on the 'left' table it could be several hundred- or thousand-fold better.
$alias.'.entity_type_id='.$entityType->getId().' AND main_table.'.$mainTableForeignKey.' = '.$alias.'.entity_id AND '.$alias.'.attribute_id = '.$attribute->getAttributeId().' AND '.$alias.'.store_id=0'

Related

How to use model CRUD properly?

I have one database table images and second one objects. images table is having object_id primary key related to objects.id field.
Now after a POST I am selecting images by posted ID's, loop through results and select appropriate objects by primary key:
// 1 query
$images = Model_Image::find(array('where' => array('approved' => 0, array('object_id', 'in', Input::post('objects'))));
foreach($images as $image)
{
// now get it's object
// 2 queries
$obj = Model_Object::find_by_pk($image->object_id);
$obj->image = 1;
// 3 queries
$obj->save();
}
The thing is, I'm wondering, how should I work this out properly - I think using CRUD is not always a good idea and might affect performance even though it looks pretty and feels good to use it. But is it really worth to sacrifice performance? Lets say, we have 10 images to edit, so that would generate 11 queries to perform a simple action.
I mean, I could simply use the following query to do it all...
UPDATE `objects` SET `image` = 1
LEFT JOIN `images` ON(`image`.`object_id` = `object.id`)
WHERE `images`.`approved` = 0 AND `images`.`id` IN ([post ids]);
So is it worth to still use CRUD in this case?

Codeigniter, join of two tables with a WHERE clause

I've this code:
public function getAllAccess(){
$this->db->select('accesscode');
$this->db->where(array('chain_code' => '123');
$this->db->order_by('dateandtime', 'desc');
$this->db->limit($this->config->item('access_limit'));
return $this->db->get('accesstable')->result();
}
I need to join it with another table (codenamed table), I've to tell it this. Not really a literal query but what I want to achieve:
SELECT * accesscode, dateandtime FROM access table WHERE chain_code = '123' AND codenames.accselect_lista != 0
So basically accesstable has a column code which is a number, let us say 33, this number is also present in the codenames table; in this last table there is a field accselect_lista.
So I have to select only the accselect_lista != 0 and from there get the corrisponding accesstable rows where codenames are the ones selected in the codenames.
Looking for this?
SELECT *
FROM access_table a INNER JOIN codenames c ON
a.chain_code = c.chain_code
WHERE a.chain_code = '123' AND
c.accselect_lista != 0
It will bring up all columns from both tables for the specified criteria. The table and column names need to be exact, obviously.
Good start! But I think you might be getting a few techniques mixed up here.
Firstly, there are two main ways to run multiple where queries. You can use an associative array (like you've started to do there).
$this->db->where(array('accesstable.chain_code' => '123', 'codenames.accselect_lista !=' => 0));
Note that I've appended the table name to each column. Also notice that you can add alternative operators if you include them in the same block as the column name.
Alternatively you can give each their own line. I prefer this method because I think its a bit easier to read. Both will accomplish the same thing.
$this->db->where('accesstable.chain_code', '123');
$this->db->where('codenames.accselect_lista !=', 0);
Active record will format the query with 'and' etc on its own.
The easiest way to add the join is to use from with join.
$this->db->from('accesstable');
$this->db->join('codenames', 'codenames.accselect_lista = accesstable.code');
When using from, you don't need to include the table name in get, so to run the query you can now just use something like:
$query = $this->db->get();
return $query->result();
Check out Codeigniter's Active Record documentation if you haven't already, it goes into a lot more detail with lots of examples.

PDOStatement::fetch() and duplicate field names

I'm working on a web application using MySQL and PHP 5.3.8. We have a mechanism to translate a simplified query instruction into a complete query string, including joins.
Since I cannot know what (normalized) tables there will be joined and what their fields are called, there may be duplicate field names. When executing PDOStatement::fetch(PDO::FETCH_ASSOC), I get an associated array of field names:
$test = $this->DBConnection->prepare("SELECT `events`.`Title`, `persons`.`Title` FROM `events` JOIN `persons` ON `events`.`HostID` = `persons`.`ID`;");
$test->execute();
$test->fetch();
But I have no way of distinguishing repeating field names, such as "title". Worse, duplicates overwrite each other:
array('Title' => 'Frodo Baggins');
In the bad old days, I ran mysql_fetch_field() on each field to get the table for each field. Please, tell me there is a better way than prefixing the fields (SELECT events.Title AS eventsTitle;).
Your help is greatly appreciated!
Give them aliases in the query so they won't be duplicates:
SELECT events.Title AS eTitle, persons.Title AS pTitle FROM ...
Then the row will be:
array('eTitle' => 'Hobbit Meeting', 'pTitle' => 'Frodo Baggins');
The alternative is to fetch the result as an indexed array rather than associative:
$test->fetch(PDO::FETCH_NUM);
Then you'll get:
array('Hobbit Meeting', 'Frodo Baggins');
and you can access them as $row[0] and $row[1].

mysql | PHP | Join within own table

i dont know if i am doing right or wrong, please dont judge me...
what i am trying to do is that if a record belongs to parent then it will have parent id assosiated with it.. let me show you my table schema below.
i have two columns
ItemCategoryID &
ItemParentCategoryID
Let Suppose a record on ItemCategoryID =4 belongs to ItemCategoryID =2 then the column ItemParentCategoryID on ID 4 will have the ID of ItemCategoryID.
I mean a loop with in its own table..
but problem is how to run the select query :P
I mean show all the parents and childs respective to their parents..
This is often a lazy design choise. Ideally you want a table for these relations or/and a set number of depths. If a parent_id's parent can have it's own parent_id, this means a potential infinite depth.
MySQL isn't a big fan of infinite nesting depths. But php don't mind. Either run multiple queryies in a loop such as Nil'z's1, or consider fetching all rows and sorting them out in arrays in php. Last solution is nice if you pretty much always get all rows, thus making MySQL filtering obsolete.
Lastly, consider if you could have a more ideal approach to this in your database structure. Don't be afraid to use more than one table for this.
This can be a strong performance thief in the future. An uncontrollable amount of mysql queries each time the page loads can easily get out of hands.
Try this:
function all_categories(){
$data = array();
$first = $this->db->select('itemParentCategoryId')->group_by('itemParentCategoryId')->get('table')->result_array();
if( isset( $first ) && is_array( $first ) && count( $first ) > 0 ){
foreach( $first as $key => $each ){
$second = $this->db->select('itemCategoryId, categoryName')->where_in('itemParentCategoryId', $each['itemParentCategoryId'])->get('table')->result_array();
$data[$key]['itemParentCategoryId'] = $each['itemParentCategoryId'];
$data[$key]['subs'] = $second;
}
}
print_r( $data );
}
I don't think you want/can to do this in your query since you can nest a long way.
You should make a getChilds function that calls itself when you retrieve a category. This way you can nest more than 2 levels.
function getCategory()
{
// Retrieve the category
// Get childs
$childs = $this->getCategoryByParent($categoryId);
}
function getCategorysByParent($parentId)
{
// Get category
// Get childs again.
}
MySQL does not support recursive queries. It is possible to emulate recursive queries through recursive calls to a stored procedure, but this is hackish and sub-optimal.
There are other ways to organise your data, these structures allow very efficient querying.
This question comes up so often I can't even be bothered to complain about your inability to use Google or SO search, or to offer a wordy explanation.
Here - use this library I made: http://codebyjeff.com/blog/2012/10/nested-data-with-mahana-hierarchy-library so you don't bring down your database

Multiple(sharding ) table in a Model CakePHP

There are many tables as the following:
table_2010
table_2009
table_2008
table_2007
.
.
Using MySQL 4 + PHP5 + CakePHP 1.3
My Question is
How to treat these tables in a model?
I wanna treat like this
Table->find('all',"2010",array("conditions"=>""));
I agree with Nik -- unless you're sharding for performance reasons, I would combine all of your tables into one table, with a column for the year (if you make it an INT, it won't affect performance much).
However, if you need to shard your tables, I'd recommend that you just override the Model::find() method to accept additional parameters. In your model, write something like the pseudocode below:
function find( $type, $options = array() ) {
if( isset( $options['table'] ) ) { // this is the index where you'll pass your table name
$this->setSource( $options['table'];
}
return parent::find( $type, $options );
}
Basically the call to setSource will change your table that you are querying, at runtime. See Can a CakePHP model change its table without being re-instantiated? for more information.
For me the smarter way is to use one table - posts for example and in that table to have a special column called year. So the find will be something like:
$this->Post->find('all', array('year'=>2010));

Categories