Magento: Get collection from custom query - magento

We can write a custom query in Magento:
$write = Mage::getSingleton('core/resource')->getConnection('core_write');
$write->query("insert into tablename values ('aaa','bbb','ccc')");
Now how can I get the output of query into a collection as I get from Mage::getModel()->getCollection ?

Create an object that extends one of the base collection objects, and add your query to the load method.

Related

Laravel eloquent make visible only given attribute in one instance of model

i have instance model from
$model = Model::find(1);
for example this instance always return these attribute (some is from $append):
-id
-name
-countRelation
-description
-created_at
-updated_at
what i want is to only retrive name and description from this instance;
makeVisible only work to show hidden attribute; i don't want use makeHidden because the result of find may change if on model i add new append attribute;
Since you are appending accessors limiting the SELECT statement won't stop those from being appended to the serializied output. You can use setVisible to do this though:
$model->setVisible(['name', 'description']);
Setting what is visible this way will limit the attributes, appends and relationships that are returned in the serialized output of the Model.
You can use select to only retrieve some column in your database, it will not affect append, see the doc for more info Eloquent
$model = Model::find(1);
// to this
$model = Model::select('name', 'description')->find(1);
See Query Builder for more insight about grabbing data from database.
if you retrieve name and description only, then you may use
$model = Model::select(['name', 'description'])->find(1);
You can use select() to select only certain columns in your query.
$model = Model::select('name', 'description')->find(1);
https://laravel.com/docs/8.x/queries#specifying-a-select-clause
You can also get the Model and use functions on the model. If you have a single Model you can use get().
$model = Model::find(1)->get('name', 'description');
If you have a collection you can use ->map->only(). This maps the only function as a callback for each Model in your Collection.
$models = $models->map->only(['name', 'description']);

Laravel How to easy filtering of Eloquent all?

I have a Customer Model that it`s called like this:
$Customer = Customer::all();
How can I change if I have a filter request like "status"?
I tried this way:
$Customer = Customer::orderBy('id');
if($filter->has('active')){
$Customer->where('status',$filter->status);
}
$Customer->count();
The problem is if I don`t set any filter I don't get all Customers. And I don't want to write another if. I want to change
$Customer = Customer::orderBy('id');
to get all and if filter is set I want only filter. How to do this?
when you get the query() method of the eloquent model, you obtain a query builder for that model, all what you have to do is add wheres and orderby... to that query builder then call count() to get the count:
$customer = Customer::query()->orderBy('id');
if($filter->has('active')){
$customer= $customer->where('status',$filter->status);
}
$customerCount=$customer->count();

Adding data to an eloquent collection?

Im getting various data out of my database.
Product::with('users');
I also have toe execute a complex raw query to get back some information. This is returned as an array.
In my method I would like to get products with users and then add on the data from my raw query to this collection, but this data comes back as an array. Something like:
Product::with('users');
Product->extraData = $rawQuery;
How can I add the raw query output to my Product Collection?
By using Eloquent Facade like Product:: you will get an Eloquent Model object as a result or an Eloquent Collection object as a result, including results retrieved via the get method or accessed via a relationship.
Now, if i understand correctly, you need to add a single extraData property to Eloquent Collection model alongside with Collection items? Or you need to add extraData for each Product ?
If you need to add additional property to Eloquent Collection object, maybe it is a good idea to use a Custom Collection. Please read this section: http://laravel.com/docs/5.1/eloquent-collections#custom-collections .
<?php namespace App;
use App\CollectionWithExtraData;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function newCollection(array $models = [])
{
return new CollectionWithExtraData($models);
}
}
And maybe your CollectionWithExtraData can have let's say a
public function setExtraData() {
}
or
public $extraData = array();
If you need extraData for each Product Eloquent Model, just create a new attribute within your Eloquent Model, make it public and set your extra data when needed. Make use of setExtraData() method and $extraData property from above

Magento Collection Query

I created new customer attribute 'personal_number' and now want to show it in new column in adminhtml sales_order_grid.
I've done all stuff to show column in grid (class rewrite in config.xml), created MyName_MyModule_Block_Adminhtml_Order_Grid where need to rewrite _getCollectionClass() and _prepareColumns(). My problem is in _getCollectionClass() where I need to do database query to join customers attribute data to orders collection. Becouse I'am very new in Magento, logic of magento-way queries for me is very hard to follow. Can someone help me to write MySql query below in Magento-way to get value of my customer attribute 'personal_number' in orders grid:
SELECT Orders.*, Customers.customer_id, Custumer.personal_namber FROM Orders INNER JOIN Customers ON Orders.customer_id = Customer.customer_id
You usually don't need to change _getCollectionClass, but rather do the join on the grid, on _prepareCollection. Ie:
protected function _prepareCollection()
{
$collection = Mage::getResourceModel($this->_getCollectionClass());
//we changed mysql query, we added inner join to order item table
$collection->join(
// Alias => Table name
array('customers' => "customer/customer"),
// Join condition
'main_table.customer_id = customer.customer_id',
// Fields to select
array('personal_number'=>'personal_number');
$this->setCollection($collection);
return parent::_prepareCollection();
}
Taken from here, have a look at the full article for more help: http://inchoo.net/magento/how-to-extend-magento-order-grid/

Replace the column name in the magento collection while loading it

I have a custom module and I am loading a collection like following
$collection = Mage::getModel('module/product')->getCollection()
->addFieldToFilter('sku',$sku);
There is field named as prod_id in the database. Can I get this as entity_id while loading the collection?
If yes. Please help how to do this.
First of all all
addAttributeToFilter() is used to filter EAV collections.
addFieldToFilter() is used to filter Non-EAV collections.
EAV-models are for example product, customer, sales, etc so you can use use addAttributeToFilter() for those entities.
addFieldToFilter() is mapped to `addAttributeToFilter()` for `EAV` entities. So you can just use `addFieldToFiler().`
You can have a look in app/code/core/Mage/Eav/Model/Entity/Collection/Abstract.php where the Mapping is done:
public function addFieldToFilter($attribute, $condition = null) {
return $this->addAttributeToFilter($attribute, $condition);
}
If you are using custom module then you can directly use addFieldToFilter() with your column name
Like
$collection = Mage::getModel('module/model')->getCollection()
->addFieldToFilter('column_name',$data);
Let me know if you have any query

Resources