attribute select magento query - magento

i am trying to get this query in magento.
Select merk, option_id from catalog ....... group by option_id
Sofar i have this but it aint showing the option_id value unfortunately and also i dont know how to group by them...
i hope someone is willing to help me
[code]
<?php
function getMenuWatches(){
$collection = Mage::getModel("catalog/product")->getCollection();
$collection->addAttributeToFilter("attribute_set_id", 26);
$collection->addAttributeToSelect("option_id , merk");
return $collection;
}
$collection=getMenuWatches();
//print_r($collection);
foreach ($collection as $product){
echo $product->getOptionId();
$product->getMerk();
echo $product->getId('merk');
echo $product->getAttributeText('merk')."<br/>";
}
?>
[/code]

$collection->addAttributeToSelect(array('option_id', 'merk'));
$collection->groupByAttribute('option_id');

Attributes with multiple choices are stored as comma separated values.
So you just need add "merk" attribute in select object:
$collection->addAttributeToSelect('merk');
and when you are iterating the collection, you may retrieve options id by calling your attribute value:
// List of option_id values
$values = explode(',', $product->getMerk());
After retrieving of the values you need to retrieve option label for each option id
$attribute = $product->getResource()->getAttribute('merk');
$optionLabel = $attribute->getSource()->getOptionText($optionId);
To filter by one of the multiple values you may use:
// Creates FIND_IN_SET statement for comma-separated attribute values
$collection->addAttributeToFilter('merk', array('finset' => $optionId));

Related

Advice with Magento large productsfile csv import

I need to import 40.000 products.
These products together are generating 600.000 attribute values
There is a csv file with product info (Sku, Name, Description and Ean) and a seperate sheet with only the attributes(600K)
On each row i have:
Sku - Attribute - Value
e.g.
123 Color Green
123 Length 120
123 Size XL
456 Color White
456 Length 260
etc..
I have filtered all duplicates out which resulted in 2200 unique Attributes.
What should i Do with these attributes?
Put them all in one attributeset? Will it hurt the performance of the webshop?
And what about the attributesheet?
How should i convert the structure of the presented data so it will be usefull for for import in magent? Cause magento needs all attribute names as columnheaders?
I have tried to collect teh attribute values with VLOOKUP but run into memory problems on my MACbook Pro. Fill down one column with a formula doesn't work wit this amount of records.
Maybe there is a solution programmticly.
Thanks!
I would suggest to create product pragmatically.
Import product into a mysql table (tables) and create using magento code directly.
You can create configurable attributes and use its id when creating products.
You should think about using uRapidFlow.
While I am not a huge fan of the fact that it uses direct sql to import products, it has been around for some time and is known to be very reliable and very fast.
//add new products
$product = Mage::getModel('catalog/product');
$product->setSku($sku);
$product->setStatus(1);
$product->setName($name);
$product->setDescription($details);
$product->setShortDescription($description);
$product->setPrice(0);
$product->setTypeId('simple');
$product->setAttributeSetId(4); // enter the catalog attribute set id here
$product->setCategoryIds($categoryIds); // id of categories
$product->setWeight(1.0);
$product->setTaxClassId($taxClassId);
$product->setVisibility($visibility);
$product->setStatus($productStatus);
$product->setColor('color',$color_id); // u need to get attribute code for dropdown items
$product->setData('material', $avid);
$product->setBrand($brand);
/*$product->setStockData(
array(
'manage_stock' => 1,
'is_in_stock' => 1,
'qty' => $qty
)
);*/
// assign product to the default website
$product->setWebsiteIds(array(1,2,3,4));
try{
$product->save();
$i++;
;
}catch (Exception $e) {
echo Mage::logException($e->getMessage());
}
$id = Mage::getModel('catalog/product')->getIdBySku(trim($sku)); //get product id after create
//add dropdown items for attribute u created already, u need to make this as function to get option id before add a product
$attribute_model = Mage::getModel('eav/entity_attribute');
$attribute_options_model= Mage::getModel('eav/entity_attribute_source_table') ;
$attribute_code = $attribute_model->getIdByCode('catalog_product', $attribute_code);
$attribute = $attribute_model->load($attribute_code);
$attribute_table = $attribute_options_model->setAttribute($attribute);
$options = $attribute_options_model->getAllOptions(false);
foreach($options as $option)
{
if (strtolower($option['label']) == strtolower($label))
{
$optionId=$option['value'];
break;
}
}
//u need to run thru a loop to add products

Only one row is returned using where in with comma seperated value in Laravel raw query

I am developing a php project using Laravel 5.2. In my app I am retrieving records from database using manual query. But I am having a problem with retrieving records by using where in statement with csv.
Example how I am retrieving
$csv = "1,3,5";
$sql = "SELECT * FROM `items` WHERE `id` IN (?)";
$rows = DB::select($sql,[$csv]);
As you can see above I am retrieving three rows. But it returns only one row where id is 1. Why is that?
You can't do it like that. Each entry in your csv is a separate parameter, so for your code you would actually need IN (?, ?, ?), and then pass in the array of values. It would be pretty easy to write the code to do this (explode the string to an array, create another array of question marks the same size, put it all together).
However, you are using Laravel, so it would be easier to use the functionality Laravel provides to you.
Using the query builder, you can do this like:
$csv = "1,3,5";
// turn your csv into an array
$ids = explode(",", $csv);
// get the data
$rows = DB::table('items')->whereIn('id', $ids)->get();
// $rows will be an array of stdClass objects containing your results
dd($rows);
Or, if you have an Item model setup for your items table, you could do:
$items = Item::whereIn('id', $params)->get();
// $items will be a Collection of Item objects
dd($items);
Or, assuming id is the primary key of your items table:
// find can take a single id, or an array of ids
$items = Item::find($params);
// $items will be a Collection of Item objects
dd($items);
Edit
If you really want to do it the manual way, you could use a loop, but you don't need to. PHP provides some pretty convenient array methods.
$csv = "1,3,5";
// turn your csv into an array
$ids = explode(",", $csv);
// generate the number of parameters you need
$markers = array_fill(0, count($ids), '?');
// write your sql
$sql = "SELECT * FROM `items` WHERE `id` IN (".implode(',', $markers).")";
// get your data
$rows = DB::select($sql, $ids);

Magento - get order id from increment id

How do you get the Order Id from magento Order Increment Id?
I can use the following get the product id from SKU:
$product_id = Mage::getModel('catalog/product')->getIdBySku('ABCD1234');
The above example lets me get just the database entity_id of a product without loading everything. I want to achieve the same for order.
In a Magento model, the load method can take an optional second argument of what attribute to load by.
So, in your case, the following should work:
$order = Mage::getModel('sales/order')->load($incrementId, 'increment_id');
$id = $order->getId();
In more complex cases, e.g. where you want to load by a combination of fields, you can load a collection, and get the first element of the collection. In your case, you'd do it like this:
$order = Mage::getModel('sales/order')->getCollection()
->addFieldToFilter('increment_id', $increment_id)
->getFirstItem();
You can load an order from the IncrementId.
$orderIncrementId = "1000001";
$order = Mage::getModel('sales/order')->loadByIncrementId($orderIncrementId);
echo $order->getId();
If you want to fetch only order_id then simply use mysql query, if you want order_id in for loop, it is not load entire order object and it is very quick and fast, you don't need to load order object model.
$write = Mage::getSingleton('core/resource')->getConnection('core_read');
$result=$write->query("SELECT entity_id FROM `sales_flat_order` WHERE `increment_id` = 'your increment id' ");
$row = $result->fetch();
echo $row['entity_id'];

How do I check whether a value in a query result is null or not? - Active Record - CodeIgniter

I wanted to know how to check whether there is a value present in a table (managers) and then add a 'yes' or 'no' string depending on if there is a value in that table or not.
$this->db->select('employees.first_name, employees.last_name, departments.department_name, departments.department_numb, titles.title');
$this->db->from('employees');
$this->db->where('first_name', $firstname);
$this->db->where('last_name', $lastname);
$this->db->join('department_manager', 'department_manager.emp_numb = employees.emp_numb', 'inner');
$this->db->join('departments', 'departments.department_numb = department_manager.department_numb', 'inner');
$this->db->join('titles', 'titles.emp_numb = employees.emp_numb', 'inner');
$this->db->where('department_name', $dept);
$this->db->where('title', $jobtitle);
$result = $this->db->get();
$data = array();
foreach($result->result() as $row)
{
$entry = array();
$entry['firstname'] = $row->first_name;
$entry['lastname'] = $row->last_name;
$entry['jobtitle'] = $row->title;
$entry['dept'] = $row->department_name;
$entry['deptid'] = $row->department_number;
//$entry['ismanager'] =
$data[] = $entry;
}
return $data;
I want to check whether an employee is present in the table 'department_manager' which is joined by an employees number. So if that employee number is not present in the table 'department_manager' then I want to insert in the array index $entry[ismanager'] a string which says 'no', and if the employee number is present in the table 'department_manager' then I want $entry['ismanager'] to hold the string 'yes'.
But I'm confused as to how to check that the employee is present or not in that table. Do I do it in the active record query or in the foreach loop? And if it is done in the foreach loop then how do I make that comparison as the query is completed?
Why have a field that is basically a calculated value? That's like having fields for quantity per box, quantity of boxes then saving the total items to a third field. Never save to the database something you can gain access to via a quick query. In your query above it's as simple as changing the dept manager join to a left join, including the dept manager id and saying if that field is blank in a record the person is not a manager. Using a LEFT join will return all records whether they have an entry in the management table or not.
Add: department_manager.emp_numb to the select.
The Join:
$this->db->join('department_manager', 'department_manager.emp_numb
= employees.emp_numb', 'left');
Then in the foreach:
if(!$row->department_manager.emp_numb)
{
this person is not a manager;
}
If you feel you really must have that extra field then you can still populate it with the method above.
If you are using MySQL, I think you are looking for:
IFNULL(expr1,expr2)
where:
expr1 == null condition (in your case NULL)
expr2 == replacement value
Source: Control Flow Functions

Magento Filter By Relative Value

I would like to filter a collection by relative value per that row. For example,
SELECT * FROM table WHERE column_1 > column_2
The only thing I know how to do in Magento would be
$q = Mage::getModel('table')->getCollection()
->addAttributeToFilter('column_1', array('gt' => $some_number));
or something of that sort. I can only give it a value to compare against, not a column name. I also looked at the Zend_Db_Select method at the where clause but didn't find anything that would help. Do I actually have to go all the way down to a direct SQL query (something which is, of course, avoided at all costs)? (I'm running Magento 1.3.2.4)
Thank you.
Try something like
$q = Mage::getModel('table')->getCollection()
->addAttributeToSelect('column_1')
->addAttributeToSelect('column_2')
->addAttributeToFilter('column_1', array('gt' => Zend_Db_Expr('`column_2`')));
OK, this is probably not the ideal solution, but it's one way of getting what you need.
This is how I got a collection of products that were on sale, where a products final price is lower than its price.
I first made a new empty data collection. Then defined the collection I was going to loop through filtering what I could first. After that I looped through that collection and any products that matched my requirements got added to the empty collection.
$this->_itemCollection = new Varien_Data_Collection();
$collection = Mage::getResourceModel('catalog/product_collection');
$collection->setVisibility(Mage::getSingleton('catalog/product_visibility')->getVisibleInCatalogIds());
$category = Mage::getModel('catalog/category')->load($this->getCategoryId());
$collection = $this->_addProductAttributesAndPrices($collection)
->addStoreFilter()
->addCategoryFilter($category)
->addAttributeToSort('position', 'asc');
$i=0;
foreach($collection as $product){
if($product->getFinalPrice() > $product->getPrice() && !$this->_itemCollection->getItemById($product->getId())){
$this->_itemCollection->addItem($product);
$i++;
}
if($i==$this->getProductsCount()){
break;
}
}
$this->setProductCollection($this->_itemCollection);

Resources