function getIdModelsSliderJuwels(){
$collection = Mage::getModel("catalog/product")->getCollection();
$collection->addAttributeToFilter("attribute_set_id", 27);
$collection->addAttributeToSelect('modellijnen');
// $collection->setRandomOrder();
// $collection->getSelect()->limit( 5 );
return $collection;
}
Hi there,
I'd like to know how to set a limit to your query running in Magento because
$collection->getSelect()->limit( 5 ); doesn't work.
Also how to select randomly, $collection->setRandomOrder(); also doesn't work.
txs.
setRandomOrder does not work for collections of products, only for related products. You'll have to add it yourself with this code:
$collection->getSelect()->order(new Zend_Db_Expr('RAND()'));
A shortcut for setting both page size and number at the same time is:
$collection->setPage($pageNum, $pageSize);
As clockworkgeek said, use the $collection->getSelect()->order(...) method to randomize the order. To limit it to just $n number of items you can also use
$collection->getSelect()->limit($n);
try to use
$collection->setPageSize(5)->setCurPage(1);
Using ORDER BY RAND() to return a list of items in a random order will require a full table scan and sort. It can negatively affect performance on large number of rows in the table.
There are several alternative solutions possible of how to optimize this query. Magento provides a native solution for that.
The orderRand() method of Varien_Db_Select and the database adapter allows to specify a random order and leverage index for ORDER BY. Specify a name of some integer indexed column to be used in the ORDER BY clause, for example:
$collection->getSelect()->orderRand('main_table.entity_id');
See Varien_Db_Adapter_Pdo_Mysql::orderRand() for implementation details.
Related
I have the following relations
Transaction Table is the parent table for ETransaction and ATransaction and belongs to transactions table
$transactionA= Transaction::with('tAccount')->has('tAccount')->get();
$transactionE= Transaction::with('tExchange')->has('tExchange')->get();
$collection = collect([$transactionE,$transactionA]);
$sorted = $collection->sortBy('created_at') do not work for me
The main problem you encounter isn't necessarily about sorting, but about building up the initial collection.
Right now, you make two collections, transactionA and transactionE. You then initialize a third collection collection that contains both transactionA and transactionE.
You can think of this as transactionA being a box of records, and transactionE being another box of records. What you want is one big box of records, but the current code puts both boxes in another, bigger box. When sorting the bigger box, all you sort is the order in which the smaller boxes end up in the bigger box.
What you presumably want instead, is to merge the contents of both boxes and sort the ensemble. You can do so by merging the two collections:
$collection = $transactionA->merge($transactionE);
I'm not sure why you even need separate queries. Stratadox's answer shows how to query, merge and sort, but you can do that in a single query using Eloquent:
$collection = Transaction::with(["tAccount", "tExchange"])
->has("tAccount")
->orHas("tExchange")
->orderBy("created_at")
->get();
In a single query, this will look for all Transaction records that have either a tAccount or tExchange record associated, sort it by the created_at timestamp and return it in a single call. Pushing the logic to the Collection class can be inefficient, so let the database handle it when possible.
I am trying to do get all the latest items and sort by id descending (i.e. get all items that were just added with a limit and offset).
So I did this:
$products = Product::all()
->slice($request->get('offset'))
->take($request->get('limit'))
->sortByDesc('id')
->toBase();
However it seems when I have more that that limit, then I dont have the right order. It gets me say 10 products but not sorted corrected. Any idea how to do this with Eloquent ORM?
You are probably intending to have the database handle the offset and skipping and ordering instead of pulling all the possible records then taking only what you want, then sorting them ... if you were going to do it your way you would need to sort before you skip and take, by the way.
Using the database to the the filtering and ordering:
$products = Product::skip($request->input('offset'))
->take($request->input('limit'))
->orderBy('id', 'desc')
->get();
I think the issue is you're using ::all() first, which returns all Product instances in a Collection, then using collection methods. Since these methods act in order of usage, you're slicing and offsetting before sorting, so you'll get the same products each time. Use proper Builder syntax to handle this properly and more efficiently:
$products = Product::offset($request->input("offset"))
->limit($request->input("limit"))
->orderBy("id", "DESC")
->get();
Because this is a Builder instance, the query will be compiled and executed according to your Database's grammar logic, and in a single query. There's nothing wrong in using Collection logic, you'd simply have to use the correct order of methods (sortByDesc() first, then slice(), then take()), but this is incredibly inefficient as you have to handle every Product in your database.
I have implemented laravel dataTable as a service.
The initial two columns are actual id and names so, I am able to sort it asc/desc after the table renders.
But the next few columns renders after performing few calculations, i.e. these values are not fetched directly from any column rather it is processed.
I am unable to sort these columns where calculations were performed, and I get this error. And I know it is looking for that particular column for eg outstanding_amount which I don't have in the DB, rather it is a calculated amount from two or more columns that are in some other tables.
Any Suggestions on how to overcome this issue?
It looks like you're trying to sort by values that aren't columns, but calculated values.
So the main issue here is to give Eloquent/MySql the data it needs to provide the sorting.
// You might need to do some joins first
->addSelect(DB::raw('your_calc as outstanding_amount'))
->orderBy('outstanding_amount') // asc can be omitted as this is the default
// Anternative: you don't need the value sorted by
// Don't forget any joins you might need
->orderByRaw('your_calc_for_outstanding_amount ASC')
For SQL functions it'll work as follow
->addSelect(DB::raw('COUNT(products.id) as product_count'));
->orderByRaw(DB::raw('COUNT(products.id)'),'DESC');
I have more or less inherited a Magento site, which seems to be using the Mageworx Extended Orders extension for the order grid in the admin area.
Client would like the columns to be rearranged, eg, move Email over beside Voucher. In the System Config you can select columns but there doesn't seem to be any way of ordering them. I have searched through the code and tried editing code\local\MageWorx\Adminhtml\Block\Orderspro\Sales\Order\Grid.php to no avail.
I also looked in the database but couldn't find a table which might have the columns selected so that I could order them.
Thanks.
As it happens it was that file, MageWorx\Adminhtml\Block\Orderspro\Sales\Order\Grid.php, that I needed to edit. I took out the loop and just commented out the fields I didn't want showing and put the rest in the required order
You can change it in the file: app/code/local/MageWorx/OrdersPro/Block/Adminhtml/Sales/Order/Grid.php in the _prepareColumns() method.
At the moment changing columns order is quite a challenge and can be done only this way:
$listColumns = $helper->getGridColumns();
$listColumnsChanged = $listColumns; // create a copy of $listColumns
$listColumnsChanged[0] = $listColumns[3];
$listColumnsChanged[3] = $listColumns[0]; // interchange the columns that have id 3 and 0
var_dump($listColumns); // var_dump will let you learn ID of the column you need
foreach ($listColumnsChanged as $column) { // change foreach for getting to $listColumnsChanged
How do I customise the starting number for orders, invoices etc in Magento 1.5?
From magento's forum:
by LindyKyaw (Magento Team Member), changing start number (through sql query):
There is a table in the database which stored increment id of order.
It is called “eav_entity_store” table.
You can check which entity type id belongs to which entity by looking at
eav_entity_type table.
You can run following query to update last increment id for the order.
update eav_entity_store
inner join eav_entity_type on eav_entity_type.entity_type_id = eav_entity_store.entity_type_id
set eav_entity_store.increment_last_id=3001
where eav_entity_type.entity_type_code='order';
by FOOMAN (active contributor), changing start number (through db management tool) and removing "0"s at the beginning:
With a tool like phpmyadmin look at your database. In the table
eav_entity_type you will find all entity types listed. The one of interest to
change where the order number starts is order sales/order. Remember the
entity_type_id (in my install it is 11). To remove the leading zeros
(padding) set increment_pad_length to 1.
Next go to the table eav_entity_store. Look up the entity_type_id. Now you
can change the value of increment_prefix and increment_last_id. If you wanted to
have your next orderId to be 15000 set increment_last_id to 14999 and
increment_prefix to 0.
Additionally you need to make a copy of this file
/app/code/core/Mage/Eav/Model/Entity/Increment/Abstract.php
to
/app/code/local/Mage/Eav/Model/Entity/Increment/Abstract.php
public function getPadLength()
{
$padLength = $this->getData('pad_length');
if (empty($padLength)) {
$padLength = 0;
}
return $padLength;
}
...
public function format($id)
{
$result= str_pad((string)$id, $this->getPadLength(), $this->getPadChar(), STR_PAD_LEFT);
return $result;
} Hope That Helps
Actually with the newer versions (and probably in 1.5 as well), there is an easier way to change it. In PHPMyAdmin, or your mysql client, go to the eav_entity_type table. Locate the table in the entity_type_code column (probably order), and set the increment_pad_length to be whatever you would like, as well as the increment_pad_char.
Then you don't have to rewrite core code - a win-win.
JMax
Magento Order No
It's simple....
go to phpmyadmin
select your datbase and then select the table "eav_entity_store"
in this table, change the increment_last_id (for example, I have set 3456767 in my table)
after that I create a new order. Now my orders start from the number 346768
There is actually a good extension for accomplish this task.
It allows you to customize the order ID in a lot of different way:
for example you can use a combination of:
number like year,month,,day,hr,sec,
use a custom counter (you can decide the starting number )
a combination of all above methods
add some custom string in any position of the order ID
This is the ext. on Magento connect:
http://www.magentocommerce.com/magento-connect/custom-order-id-8210.html
I personally tried it and it very good ( works fine with all my payment methods and I had no issue at all )