Converting an array to a collection in Magento - magento

I have an array object that is an output of a magento fetchall from DB and i want this to be converted to an object of a Collections class so that i can implement pagination and use this collection to join with other tables. Can you please help me here ? been stuck for a long time now !!

In order to convert an array to a collection object:
1> Create an instance of Varien_Db_Collection
$collection = new Varien_Data_Collection();
2> Create an instance of Varien_Object and set the array data
$rowObj = new Varien_Object();
$rowObj->setData($row);
3> Finally add the Varien_Object to Collection instance
$collection->addItem($rowObj);
4> Now $collection is a collection object.

Magento hasn't a built in conversor for that, but you can write you query using Collections, or load the Collection based on all ids from your array.

Also, populating a collection can be done with the addItem method.

If you have an array of ids $product_ids, you can use:
$collection = Mage::getModel('catalog/product')->getCollection()
->addIdFilter($product_ids);

Related

Best approcah for getting the object in the foreach loop in laravel using eloquent?

I have some properties and i want to get the object for each property, currently, I am using the eloquent in the foreach loop like this as shown in the image that will describe the best..
but it is really not a good approach because if I have 100 published property I will making 100 calls to the DB... and that is not correct?
I need a suggestion and a proper solution to this query?
Thanks in advance
Before foreach you can get all the RentalProperty items from db like this:
$allRentalProperties = RentalProperty::all();
and in foreach loop you can get those items without connecting database like this:
$propertyObj = $allRenatalProperties -> where('id', $property['id']) -> first();
Also, you can use array shorthand.
$newArray = [];
it's much simple and readable.
You can do array pluck before loop:
$propertyIds = Arr::pluck($published_properties, 'id');
Then you can make a whereIn query to get only those data which are in $published_properties object
$propertyObj = RentalProperty::whereIn('id', $propertyIds);
Then you can access that object with id if you change array key with record id.

Laravel, how to convert a collection object into a builder object

I need to use paginate and simplepaginate on a collection, so i'm trying to convert the collection into a builder object.
To do so I am thinking of creating a function that gets the id of every item in the collection and then builds a query with it, but that seemed to me like a lot of resources waisted,
Is there a simpler way ?
A better way to do this is to build paginator object manually using the existing collection.
From the docs:
Sometimes you may wish to create a pagination instance manually, passing it an array of items. You may do so by creating either an Illuminate\Pagination\Paginator or Illuminate\Pagination\LengthAwarePaginator instance, depending on your needs.
The Paginator class does not need to know the total number of items in the result set; however, because of this, the class does not have methods for retrieving the index of the last page. The LengthAwarePaginator accepts almost the same arguments as the Paginator; however, it does require a count of the total number of items in the result set.
In other words, the Paginator corresponds to the simplePaginate method on the query builder and Eloquent, while the LengthAwarePaginator corresponds to the paginate method.
Building on what Alexey said, as alternative, you can build a Paginator from a collection manually. This is a simpler way without the waste of an additional query. e.g.
// Collection $collection
$perPage = 10;
$currentPage = Illuminate\Pagination\Paginator::resolveCurrentPage() ?? 1;
$itemsOnPage = $collection->skip(10 * ($currentPage-1))->take($perPage);
$paginatorPath = Illuminate\Pagination\Paginator::resolveCurrentPath();
$paginator = new \Illuminate\Pagination\LengthAwarePaginator(
$itemsOnPage,
$collection->count(),
$perPage,
$currentPage,
['path' => $paginatorPath]
);
Then in your view,
{!! $paginator->render() !!}

Laravel Eloquent ORM - How to get the all the properties of afrom/of a collection in a array?

$user_emails = ["email_1#domain.com", "email_2#domain.org"];
$users = Users::whereIn("email", $user_emails);
The table for users also has a phone column for each user. What's the best way to get a list/array of the phone number as an array?
$users->all()->phone(); // Like (which is not correct)
Try to use get() like :
$users = Users::whereIn("email", $user_emails)->get(['phone'])->toArray();
Or also pluck() like :
$users = Users::whereIn("email", $user_emails)->pluck('phone')->all();
Hope this helps.
Use pluck method to fetch a specific column's values and then use toArray on returned Collection object to get results as an array.
$phoneNumbers = Users::whereIn("email", $user_emails)->pluck('phone')->toArray();
You can get all column data with get()
Example:
$user = $user::where('email', $user_emails)->get();
You can get the list with foreach loop method.

Get collection sort order fields

Does anyone know of a clever way to read sort order array from Magento product collection? There's a protected property _orders in the object. I could reach it over
$collection->getSelect()->getPart('order')
but then I'd have to do string parsing.
I was hoping there was a public method of some sort that would fetch sort order info from product collection?
You can use Reflection :
$property = new ReflectionProperty(get_class($collection), '_orders');
$property->setAccessible(true);
$orders = $property->getValue($collection);
But you won't avoid some string parsing, as order values are stored in strings ($field.' '.Varien_Data_Collection::SORT_ORDER_(ASC|DESC))
For a product collection with toolbar you can ask the toolbar the current sorting order:
Mage::getBlockSingleton('catalog/product_list_toolbar')->getCurrentOrder()

Magento: Sort items of Varien Data Collection

I would like to sort a Varien_Object in Magento with a custom attribute.
I got something like this:
$thing_1 = new Varien_Object();
$thing_1->setName('Richard');
$thing_1->setOrder(2);
$thing_2 = new Varien_Object();
$thing_2->setName('Jane');
$thing_2->setOrder(1);
$collection_of_things = new Varien_Data_Collection();
$collection_of_things
->addItem($thing_1)
->addItem($thing_2);
I want to sort it ASC so that Jane can be in front of Richard
Thanks.
Varien_Data_Collection has method for sorting but this method is rendered to SQL query in the execution.
public function setOrder($field, $direction = self::SORT_ORDER_DESC)
if you additems manually it will be added with index in the order you added them so what you need to do it to sort the objects first then add them to the data collection
look at this question Sort array of objects by object fields

Resources