Magento Load Collection Using Order By - magento

My query is generating from magento collection is
$userModel = Mage::getSingleton('user/user')->getCollection()->addFieldToFilter('user_id', array('in' => array($User_Id)));
SELECT `main_table`.user_name FROM `user_table` AS `main_table` WHERE (user_id IN('1', '3', '2'));
I want to use this query:
SELECT `main_table`.user_name FROM `user_table` AS `main_table` WHERE (user_id IN('1', '3', '2')) ORDER BY FIELD(user_id , 1,3,2);
So that it will display the user name in the same order as ID's are input.
i.e. "1,3,2"
Which method is used in Magento to load collection using ORDER BY?
Thanks in advance!

You can get Zend_Db_Select from Collection and then add order to Zend_Db_Select like this question:
Zend DB Select : ORDER BY FIELD('id',some_array) - how?

Related

Equivalent ORM Query in Laravel

Following is my query:
select nonrem_id as RefID , (SELECT group_concat(concat(nonremu_updated_date, ' - ',name,' - ',ttu.nonremu_updates) SEPARATOR ',') FROM `fanda_bank_nonremit_update` as ttu left join fanda_mst_users on login_id = nonremu_createdby WHERE ttu.nonremu_cid = fanda_bank_acc_nonremitted.nonrem_id order by ttu.nonremu_id asc ) as Comments from `fanda_bank_acc_nonremitted` left join `fanda_mst_users` on `login_id` = `nonrem_created_by` where `nonrem_gl_date` >= 2017-02-01 and `nonrem_gl_date` <= 2017-05-11 and `nonrem_country` = BE
How do I write this query in Laravel Eloquent ORM. I have tried using Query builder, but I wanna know how to write this query in pure ORM.
P.S: I should not use DB::raw() anywhere.
Kindly help.
You can't, you'll need DB::raw() to build a select statement like that.
EDIT:
If you don't care about using DB::raw() on your select, then try something like this on your select:
Model::select('nonrem_id as RefID',DB::raw('(SELECT group_concat(concat(nonremu_updated_date, ' - ',name,' - ',ttu.nonremu_updates) SEPARATOR ',') FROM `fanda_bank_nonremit_update` as ttu left join fanda_mst_users on login_id = nonremu_createdby WHERE ttu.nonremu_cid = fanda_bank_acc_nonremitted.nonrem_id order by ttu.nonremu_id asc ) as Comments'))
If you are using strict mode it will throw a QueryException cause you are ordering your first query by a non selected field , to avoid this query exception configure your db connection to allow this kind of order by. You can do it on the file: config/database.php by adding this two parameters to your actual connection within your 'connections' array:
'strict' => true,
'modes' => ['STRICT_TRANS_TABLES',
'NO_ZERO_IN_DATE',
'NO_ZERO_DATE',
'ERROR_FOR_DIVISION_BY_ZERO',
'NO_AUTO_CREATE_USER',
'NO_ENGINE_SUBSTITUTION'],

Newest items and GROUP By with Eloquent

I have the following prices-table:
shop_id (int)
product_id (int)
price (float)
created (DateTime)
Every hour a cronjob checks the shops and inserts new entries (current prices) into these price-table.
Now I want to display the newest price for a product. I have to GROUP BY the shop_id because I only want one price per shop but I only want the newest entry (created).
Can I solve this with Eloquent Query-Builder or do I have to use raw SQL? Is it possible to pass the result of a raw SQL-query into a model if the columns are the same?
You can try it as:
Price::select('*', DB::raw('MAX(created_at) as max_created_at'))
->groupBy('shop_id')
->get()
Assuming model name is Price
Eloquent (purist) approach:
Price::orderBy('created', 'desc')->groupBy('shop_id')
->get('shop_id', 'price');
References:
https://laravel.com/api/5.3/Illuminate/Database/Query/Builder.html#method_orderBy
https://laravel.com/api/5.3/Illuminate/Database/Query/Builder.html#method_groupBy
https://laravel.com/api/5.3/Illuminate/Database/Query/Builder.html#method_get
*untested though
Q: Is it possible to pass the result of a raw SQL-query into a model if the columns are the same?
A: you could pass it to Model's contructor - but it might need model's field to be fillable - or hydrate a model. Alternatively, just access it like an keyed-array, ie. $something[0]['price'] <-- assuming an array of prices with price column.
I solved the problem without QueryBuilder. Instead I use a raw SQL-statement and generating the models with the hydrateRaw()-function of the Model-class.
$prices = Price::hydrateRaw( 'SELECT p.*
FROM prices p
INNER JOIN (
SELECT shop_id, max(created_at) AS max_ca
FROM prices p1
GROUP BY shop_id
) m ON p.shop_id = m.shop_id AND p.created_at = m.max_ca');

How we can write multiple select keyword in a single mysql query using Magento?

here is my query and this give proper ouput.
But How can I set it according to magento rules?
SELECT main_table.*,
(select company from sales_flat_order_address sfoa where sfoa.entity_id=sfo.billing_address_id) as bill_to_company,
(select company from sales_flat_order_address sfoa where sfoa.entity_id=sfo.shipping_address_id) as ship_to_company
FROM sales_flat_order_grid as main_table inner join sales_flat_order as sfo
on main_table.entity_id = sfo.entity_id
please help me....
Thanks & Reagards
Praful
You can use magento default connection Model
$write = Mage::getSingleton('core/resource')->getConnection('core_write');
$result=$write->query("your query as like mysql query no different");
$row = $readresult->fetch(); // this will fetch all your data

Magento filter order collection by product sku

I'm using magento 1.7 and I need to get all orders from certain increment_id containing at least one item matching a sku.
Here's what I have:
$orderCollection = Mage::getModel('sales/order')->getCollection()
->addFieldToFilter('status',
array(
'nin' => array(
'new',
'pending',
'pending_payment',
'holded',
'canceled')
))
->addFieldToFilter('increment_id', array('gteq' => $last_order));
If I add a line with:
$orderCollection->addFieldToFilter('sku', $findSku);
I will get a PHP fatal error since 'sku' is not a field. I've tried addAttributeToFilter() and it won't work either.
I know I need to build a join with another table, but I don't know how joins are made in Magento and I don't know which table I should join to.
Any help will be greatly appreciated.
SKUs are placed in order item table not in orders.
Your final query must look like this one:
SELECT o.increment_id
FROM sales_flat_order_item oi
INNER JOIN sales_flat_order o ON o.entity_id = oi.order_id
WHERE product_id=XXX
ORDER BY o.increment_id DESC;
This query can be done using nearly such syntax:
$orderItem = Mage::getModel('sales/order_item')->getCollection();
$orderItem
->getSelect()
->joinInner(array('order' => Mage::getSingleton('core/resource')->getTableName('sales/order')), 'order.entity_id = main_table.order_id' )
->where('product_id=?', $productId)
->order('main_table.order_id DESC');

Magento Get Product SELECTED ATTRIBUTE only?

Hi i'm working on an external application thats shows all the ordered items on a magento store.
The query that display the ordered product attribute is this :
select group_concat(distinct(b.value) separator '<br/>') from catalog_product_entity_varchar a , eav_attribute_option_value b , eav_attribute c
where a.value = b.option_id
and c.attribute_id = a.attribute_id
and c.is_user_defined = 1
and a.entity_id = PRODUCT_ID
This is for the attributes with type VARCHAR , i use the same query to get attributes of int and text. I just change the table name from catalog_product_entity_varchar to catalog_product_entity_int and catalog_product_entity_text.
The problem that i have is that i GET all the product attributes , manufacturer , supplier... and due to the fact that we got many stores i dont want to retrieve all the additional attributes with an additional sql where clause!
Any solution to get only selected attributes?
The below will grab the collection in PHP. You just need to change the Attribute that you select on. By adding the ->addOrderedQty, it allows the ability to get the ordered qty. Now I understand that you are using an external application. The reason that I post this is that you can load the Mage.php into your application and use this directly or you can just run this once and watch for the query in your database and then use that query to accomplish what you are looking to.
$visibility = array(
Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH,
Mage_Catalog_Model_Product_Visibility::VISIBILITY_IN_CATALOG
);
$_productCollection = Mage::getResourceModel('reports/product_collection')
->addAttributeToSelect('*')
->addOrderedQty()
->addAttributeToFilter('visibility', $visibility)
->setOrder('ordered_qty', 'desc');

Resources