Magento: Subtraction and Division on addAttributeToFilter - mysql

I'm a newbie with Magento getResourceModel, and I'm trying to add a simple filter to my query, but i can't figure that using getResourceModel.
Original Query:
$collection = Mage::getResourceModel('catalog/product_collection');
Mage::getModel('catalog/layer')->prepareProductCollection($collection);
$collection->addAttributeToFilter('promotion', 1)->setOrder('price', 'desc');
I just want add the where clause:
(`price` - `final_price`) >= (`price` * 0.4)
Someone can help me to do this?
This is all, thanks!

So finally I found the correct way to do this, sorry to delay to post the answer here and thanks #feeela.
Looking the file /lib/Zend/Db/Select.php I found that exists the where function:
public function where($cond, $value = null, $type = null)
{
$this->_parts[self::WHERE][] = $this->_where($cond, $value, $type, true);
return $this;
}
So, what we need is just add a call to this function giving the condition that we want. In my case, I just add a condition to filter products that have 40% of discount.
$collection = Mage::getResourceModel('catalog/product_collection');
Mage::getModel('catalog/layer')->prepareProductCollection($collection);
$collection->addAttributeToFilter('promotion', 1)
->addStoreFilter();
$collection->getSelect()->where( '(`price` - `final_price`) >= (`price` * 0.4)' );
So, I hope that this can be helpful for some dudes!
Grazie tutti!

Related

Natural sorting Ajax Datatables in Codeigniter

Struggling to figure out how to set natural sorting in AJAX Datatables using Codeigniter Active record.
The field that should be sorted has, in most cases, just digits...in other cases a string, so the MySQL table field is set as VARCHAR.
I need to srt naturally the field to be displayed in Datatables.
The Active record Codeigniter query is the following.
function list_all($limit,$start,$col,$dir)
{
$this->rmi_db->select ("
$this->table_dev.id,
$this->table_dev.fl,
$this->table_dev.mm,
$this->table_dev.batch,
$this->table_dev.n,
$this->table_dev.ditta,
$this->table_dev.tipo,
$this->table_dev.costruzione,
$this->table_dev.motori,
$this->table_dev.nc,
$this->table_dev.serie,
$this->table_dev.ca,
$this->table_dev.consegna,
$this->table_dev.matr_usaf AS usaf,
$this->table_dev.matr_usn AS usn,
$this->table_dev.matr_caf AS caf,
$this->table_dev.matr_raf AS raf,
$this->table_dev.codici,
$this->table_dev.note,
$this->table_dev.reg_civili,
$this->table_dev.matricola_civ,
$this->table_dev.prima_reg,
$this->table_dev.n_contratto,
$this->table_dev.data_contratto,
$this->table_dev.importo_contratto,
$this->table_dev.note_contratto,
$this->table_dev.f29,
$this->table_dev.f30,
");
$this->rmi_db->from("$this->table_dev");
$this->rmi_db->where("$this->table_dev.mm !=", "");
$this->rmi_db->limit($limit, $start);
$this->rmi_db->order_by($col, $dir);
$query = $this->rmi_db->get();
if($query->num_rows()>0)
{
return $query->result();
}
else
{
return null;
}
}
The mm field should be sorted naturally. I have no idea how and if it's possible to fix the issue.
I tried the solution in this discussion solutions, the Bin way, but the select doesn't work properly ( got 500 server error)
Thanks a lot for any help
Using Solution, Try below. It should work but not tested.
function list_all($limit,$start,$col,$dir)
{
$this->rmi_db->select ("
$this->table_dev.id,
$this->table_dev.fl,
$this->table_dev.mm,
$this->table_dev.mm, CAST($this->table_dev.mm as SIGNED) AS casted_column,//changed
$this->table_dev.batch,
$this->table_dev.n,
$this->table_dev.ditta,
$this->table_dev.tipo,
$this->table_dev.costruzione,
$this->table_dev.motori,
$this->table_dev.nc,
$this->table_dev.serie,
$this->table_dev.ca,
$this->table_dev.consegna,
$this->table_dev.matr_usaf AS usaf,
$this->table_dev.matr_usn AS usn,
$this->table_dev.matr_caf AS caf,
$this->table_dev.matr_raf AS raf,
$this->table_dev.codici,
$this->table_dev.note,
$this->table_dev.reg_civili,
$this->table_dev.matricola_civ,
$this->table_dev.prima_reg,
$this->table_dev.n_contratto,
$this->table_dev.data_contratto,
$this->table_dev.importo_contratto,
$this->table_dev.note_contratto,
$this->table_dev.f29,
$this->table_dev.f30,
");
$this->rmi_db->from("$this->table_dev");
$this->rmi_db->where("$this->table_dev.mm !=", "");
$this->rmi_db->limit($limit, $start);
$this->rmi_db->order_by($col, $dir);
$this->rmi_db->order_by('casted_column', 'ASC'); // changed
$this->rmi_db->order_by($this->table_dev.mm, 'ASC'); // changed
$query = $this->rmi_db->get(); //changed
if($query->num_rows()>0)
{
return $query->result();
}
else
{
return null;
}
}
comment if you face any issue

Eloquent select where date is equal or higher than today

Can you help me solving this problem?
I want to show all data from table 'auctions' where the date is equal or higher than today
here my current code :
public function index(Request $request)
{
if ($request->ajax()) {
$data = Auction::with('item','user')->get();
// NOT WORKING $data = Auction::with('item','user')->where('date','>=',Carbon::now())->get();
return Datatables::of($data)->addIndexColumn()->addColumn('option', function($row){
$btn = 'AJUKAN HARGA';
return $btn;
})->rawColumns(['option'])->make(true);
}
return view('bid.index');
}
Please anyone help me,, maybe you can rewrite the variable $data or any... thanks!
Thanks for Romeo Sierra, because of you i can think about this one.
Its done guys by this one
$data = Auction::with('item','user')->whereDate('date','>=',Carbon::now()->toDateString())->get();
dont forget to include
use Carbon\Carbon;
use this
$data=\App\Auction::where('date',CURDATE() >= $date)->get();

What is the best way to add some codes before a function in cakephp3?

I want to convert $token to lower case before I call the __($token) function.
How can I do this in a clean manner?
Possible solutions:
1. Manipulation the original function.
public function __($token, $args = null) {
if (!$token) {
return null;
}
$lowerCase = strtolower($token);
$arguments = func_num_args() === 2 ? (array)$args : array_slice(func_get_args(), 1);
$translation = I18n::translator()->translate($lowerCase , $arguments);
return $translation == $lowerCase ? $token : $translation;
}
I think it's not a good idea.
2. Using somethings like beforeFilter. It's better way.
3. Redeclaring function where I need. It's really bad idea :)
Any solution or best solution is appreciated.

Laravel - How to paginate here?

I have this code and I want to paginate $shares.
How can I archive this?
$level = Share::join('follows', 'shares.user_id', '=', 'follows.user_id')
->where('follows.follower_id', Auth::user()->id)
->where('follows.level', 1)
->get(array('shares.*'));
//get 10% of shares
$count = Share::count()/10;
$count = round($count);
$top10 = Share::orderBy('positive', 'DESC')
->take($count)
->get();
$shares = $top10->merge($level);
//get only unique from shares
$unique = array();
$uniqueShares = $shares->filter(function($item) use (&$unique) {
if (!in_array($item->id, $unique)) {
$unique[] = $item->id;
return true;
} else {
return false;
}
});
//order by id
$shares = $uniqueShares->sortBy(function($share)
{
return -($share->id);
});
return View::make('layout/main')
->with('shares', $shares);
lots of reudandant unnecessary codes here.
1st:
$level = Share::join('follows', 'shares.user_id', '=', 'follows.user_id')
->where('follows.follower_id', Auth::user()->id)
->where('follows.level', 1)
->get(array('shares.*'));
Why you are taking ALL the records only to discard it later?
2nd:
$shares = $top10->merge($level); Why you are merging the two arrays?
3rd:
$uniqueShares = $shares->filter(function($item) use (&$unique) {
if (!in_array($item->id, $unique)) {
$unique[] = $item->id;
return true;
} else {
return false;
}
});
You HAD to wrote this snippet because above in 2nd, you merged the two arrays which will yield duplicated entries. So why merging?
4th:
//order by id
$shares = $uniqueShares->sortBy(function($share)
{
return -($share->id);
});
And here comes the actual data which you actually want.
So let's recape
You need
10% of total shares
order by some positive column
order by amount of shares perhaps as i am guessing.
To use the inbuilt paginate(), you'l need paginate() that's a must.
Rest is simple.
count the total result. round(Share::count()/10)
put it in paginate() as the 1st arguement.
Add the order by clause whichever is necessary.
looking at the code, it doesn't look like you will/should have duplicated data which may haved added the distinct and group by clause.
use remember in Share::count()/10; to Cache it. You don't need to run the query over and over again.
and you're done.
The way you are merging your queries you may need to manually create it the pagination in your blade, then send a variable to "take" the next set you want.
Read the Laravel Docs for more info on implementing it into your views and manually creating it.
http://laravel.com/docs/pagination
Try this, should be good to go
Share::join('follows', 'shares.user_id', '=', 'follows.user_id')
->where('follows.follower_id', Auth::user()->id)
->where('follows.level', 1)
->paginate(20);
Maybe you would like to specify columns to select in select() method.

Magento: Get simple product color from custom table

I'm really struggling with this in Magento 1.10 Enterprise. I have a array of simple products color ids and I want to use this id to query the atb_color table. Raw query:
SELECT description FROM atb_colors WHERE option_id = 'my_color_id'
Here is a method I was trying to build:
public function getColorData($product){
$ids = $product->getTypeInstance()->getUsedProductIds();
foreach($ids as $id){
$simpleproduct = Mage::getModel('catalog/product')->load($id);
-->Query using my_color_id
}
}
I can use this to get name and quantity. If I put this in the foreach loop:
echo $simpleproduct->getName()." - ".(int)Mage::getModel('cataloginventory/stock_item')->loadByProduct($simpleproduct)->getQty() . '<br />';
How would I run this query. Forgive me I am very new to Magento. It's somewhat difficult to grasp some of it. But I'm on a deadline to finish this one section of displaying color and size. Any help? Please, please!!
Thanks in advance
This is the weirdest hack, but if you are really in big hurry
public function getProductCustomColor($product)
{
$ids = $product->getTypeInstance()->getUsedProductIds();
foreach($ids as $id){
$simpleProduct = Mage::getModel('catalog/product')->load($id);
$select = $product->getResource()->getReadConnection()->select()
->from('atb_colors', array('description'))
->where('option_id = :my_color_id');
$colorDescription = $product->getResource()->getReadConnection()
->fetchOne($select, array('option_id' => $simpleProduct->getYourColorId()));
// ...
}
}
To everyone: never write code for magento in this way.