Get Magento 2 collection based on final_price - collections

I have the following code to get a Magento 2 product collection:
<?php namespace Qxs\Related\Block;
class Related extends \Magento\Framework\View\Element\Template
{
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
\Magento\Catalog\Model\Product\Attribute\Source\Status $productStatus,
\Magento\Catalog\Model\Product\Visibility $productVisibility,
\Magento\Framework\Registry $registry,
array $data = []
)
{
$this->_productCollectionFactory = $productCollectionFactory;
$this->productStatus = $productStatus;
$this->productVisibility = $productVisibility;
$this->_registry = $registry;
parent::__construct($context, $data);
}
public function getProductCollection()
{
try {
$product = $this->_registry->registry('current_product');
$range_percentage = 35;
$price_temp = round($product->getFinalPrice() / 100 * $range_percentage);
$price_from = $product->getFinalPrice() - $price_temp;
$price_to = $product->getFinalPrice() + $price_temp;
$categories = $product->getCategoryIds();
$collection = $this->_productCollectionFactory->create();
$collection->addAttributeToSelect('*')
->addCategoriesFilter(['in' => $categories])
->addPriceDataFieldFilter('%s >= %s', ['min_price', $price_from])
->addPriceDataFieldFilter('%s <= %s', ['min_price', $price_to])
->addMinimalPrice()
->addAttributeToFilter('entity_id', ['neq' => $product->getId()])
->addAttributeToFilter('status', ['in' => $this->productStatus->getVisibleStatusIds()])
->setVisibility($this->productVisibility->getVisibleInSiteIds())
->setPageSize(5);
return $collection;
} catch (\Exception $e) {
var_dump($e->getMessage());
}
}
}
Code above is updated with a working example
It will return a result with addtofieldfilter 'price' but it does not work with final_price attribute. I need to sort based on final_price because configurable products don't have a price. The code returns: invalid attribute name.
How can I filter on price range in final_price attribute?
Thanks,

The final_price is part of the price index tables, so you can't work with it the same way as you would do with fields and attributes. You need to join in the price index to be able to filter and sort based on final_price. Luckily, Magento has added a few nifty functions for us to use on the product collection; addPriceDataFieldFilter() and addFinalPrice().
Solution
To be able to achieve the logic you describe above, you would want to change your code to something like this:
$collection = $this->_productCollectionFactory->create();
$collection->addAttributeToSelect('*')
->addCategoriesFilter(['in' => $categories])
->addPriceDataFieldFilter('%s >= %s', ['final_price', $price_from])
->addPriceDataFieldFilter('%s <= %s', ['final_price', $price_to])
->addFinalPrice()
->addAttributeToFilter('entity_id', ['neq' => $product->getId()])
->addAttributeToFilter('status', ['in' => $this->productStatus->getVisibleStatusIds()])
->setVisibility($this->productVisibility->getVisibleInSiteIds())
->setPageSize(5);
Note the order of the functions. You must always call addFinalPrice() after all of the addPriceDataFieldFilter() or else the filter won't be applied.
Bonus
If you want to sort by final_price, you can add following code after addFinalPrice():
$collection->getSelect()->order('price_index.final_price ASC');
References
https://github.com/magento/magento2/blob/2.2.9/app/code/Magento/Catalog/Model/ResourceModel/Product/Collection.php#L1465
https://github.com/magento/magento2/blob/2.2.9/app/code/Magento/Catalog/Model/ResourceModel/Product/Collection.php#L2265

Related

How to format hreflang from "en-ae" to "en-AE" (WordPress+Rank Math+WPMLl)?

I need to set it by the technical task.
I've found only
function hrefs_to_uppercase($hrefs) {
$hrefs = array_change_key_case($hrefs,CASE_UPPER);
return $hrefs;
}
add_filter( 'wpml_hreflangs', 'hrefs_to_uppercase' );
But it makes all characters uppercase - "EN-AE".
Tried manually in wpml settings- didn't help
You can simply replace the array key with the following code:
function hrefs_to_uppercase($hrefs) {
$hrefs['en-AE'] = $hrefs['en-ae'];
unset($hrefs['en-ae']);
return $hrefs;
}
add_filter( 'wpml_hreflangs', 'hrefs_to_uppercase' );
if you want to make every array key have an uppercase second part (e.g. from en-us to en-US), you can use the codes below (assumed all your keys have a similar structure like en-us):
function hrefs_to_uppercase($hrefs) {
foreach ($hrefs as $key => $val) {
$key_tokens = explode('-', $key);
$new_key = $key_tokens[0] . '-' . strtoupper($key_tokens[1]);
$hrefs[$new_key] = $hrefs[$key];
unset($hrefs[$key]);
}
return $hrefs;
}
add_filter( 'wpml_hreflangs', 'hrefs_to_uppercase' );
I solved like that for now, maybe right-maybe not
jQuery('[hreflang*="en-ae"]').each(function(){
// Update the 'rules[0]' part of the name attribute to contain the latest count
jQuery(this).attr("hreflang",'en-AE');
});

How to get value from a field key (Ninja Forms)

Having a try with Ninja Forms, I’m actually able to get value from a field ID using $form_data array variable.
function my_ninja_function( $form_data ) {
$my_field_id = 1;
$my_value_from_field_id = $form_data['fields'][$my_field_id]['value'];
echo $my_value_from_field_id;
// output value is possible
}
And now trying to get value from a field key, without success...
$my_field_key = 'my_key';
$my_value_from_field_key = $form_data['fields'][$my_field_key]['value'];
echo $my_value_from_field_key;
// output value is not possible
with a little more effort...
$form_fields = $form_data['fields'];
foreach( $form_fields as $field ){
$field_value = $field['value'];
$field_key = $field['key'];
$data[$field_key] = $field_value;
};
$my_value_from_key = $data['my_key'];
echo $my_value_from_key;
// output is possible
It works!
By value I'm assuming you mean the field's label. You can get a field's label from the field's settings like this:
$form_id = 1;
$form_fields = Ninja_Forms()->form($form_id)->get_fields();
foreach( $form_fields as $field ) {
$model = $field->get_settings();
$label = $model['label'];
}
if you really do mean value, then perhaps you are referring to a form submission's field value. You can get those like this:
$sub_id = 1; // Need to know the submission's ID
$sub = Ninja_Forms()->form()->sub($sub_id)->get();
$form_id = 1;
$form_fields = Ninja_Forms()->form($form_id)->get_fields();
foreach( $form_fields as $field ) {
$model = $field->get_settings();
$value = $sub->get_field_value($model['key']); // User submitted value
}
Note that NinjaForms has added field keys in version 3 after I made the suggestion, as previous versions had no unique field identifier which made exporting/importing fields and forms very problematic.

get count with hasMany not working yii2

I have CLub model (clubs) hasMany with User model like
Club n-n User
and I have UserClub model with columns: id, club_id, user_id, etc
In Club model
public function getCountUsers()
{
return $this->hasMany(UserClub::className(), ['club_id'=>'id'])->count();
}
I wanna count all User on Club as code:
$query = Club::find()
->joinWith(['countUsers']);
// ->with('countUsers');
->all();
so it is not working and throwing an error
Club has no relation named \"countUsers\"."
Because it isn't a relation as it does not return a model object or an array of model objects, instead you are using ->count() that makes it return a string that contains the total count for the user against the club.
If you are looking to get a count for the users against all the Clubs you can use the currently defined relation like $club->countUser see below.
$clubs=Club::find()->all();
foreach($clubs as $club){
echo $club->countUser;
}
or change the relation to
public function getCountUser(){
return $this->hasMany(UserClub::className(), ['club_id'=>'id']);
}
and use it like
$clubs=Club::find()->all();
foreach($clubs as $club){
echo count($club->countUser);
}
or like below
$clubs=Club::find()->all();
foreach($clubs as $club){
echo $club->getCountUser()->count();
}
EDIT
You are actually trying to transform the following query using ActiveRecord as far as I understood from the discussion.
SELECT clubs.id, count(user_clubs.id) as total
FROM
clubs
left join user_clubs on clubs.id = user_clubs.club_id
group by clubs.id
if that is correct you can use the following
Clubs::find ()
->alias ( 'c' )
->select ( [ new \yii\db\Expression ( 'c.[[id]], count(uc.[[id]]) as total' ) ] )
->leftJoin ( '{{%user_clubs}} uc' , 'uc.club_id=c.id' )
->groupBy ( 'c.id' )
->all ();
Note : You have to do one more thing you have to add a public property $total inside your Club model and add it to safe rules, because you are selecting the count as an alias total and until unless you define it inside the model the result set won't show you the count, so add the following inside the Club model.
public $total;
under rules
[[other fields...,'total'] , 'safe' ] ,
EDIT2
For some reason, I have a feeling that you are trying to count by specifying a relation instead of specifying the ->leftJoin () with the table user_clubs in the query.
If that is so then you have to change your relation getUserCount() you should better give a meaningful name that describes it. i would rename it to getClubUsers()
public function getClubUsers(){
return $this->hasMany(UserClub::className(), ['club_id'=>'id']);
}
After this, you still have to declare a public property $total as I described before inside your Club model, and add it to safe rules.
Now you can write your query in the following way
Clubs::find ()
->alias ( 'c' )
->select ( [ new \yii\db\Expression ( 'c.[[id]], count(cu.[[id]]) as total' ) ] )
->joinWith( ['clubUsers cu'] )
->groupBy ( 'c.id' )
->all ();
You can do this with join, in my case i get users who have more than 0 referrals.
$users = User::find()->with('referrals')
->from(User::tableName() . ' t')
->join('left join',User::tableName().' r','r.Deeplink = t.ReferralID')
->select('t.*,count(r.ID) as ct')
->groupBy('t.ID')
->andFilterHaving(['>','ct',0])
->all();
Hi your relation is correct check you error Club has no relation named \"countUsers\"."
Means you are calling a relation which not exist :
change query like this, Relation name should be in Club Model
public function getCount(){
return $this->hasMany(UserClub::className(), ['club_id'=>'id']);
}
$clubs=Club::find()->all();
foreach($clubs as $club){
echo count($club->getCount);
}
$query = Club::find()
->joinWith(['count']);
// ->with('countusers');
->all();
If you want count just do like this .
Load the Club model .
$club_model = Club::find()
$count = club_model->count;

get_categories order by meta key issue?

I'm trying to search for a way to order categories by meta value. From what I read, it seems like I can use:
get_categories('child_of=92&hide_empty=false&orderby=meta_value&meta_key=date&order=ASC');
However, this does not work at all, the categories are still not in the order I want. I wonder how I can:
correct this to make it work
print out the sql to see what is really going on inside?
Thank you very much in advance.
First of all, I must mention that I'm using the module custom category fields, and second of all I'm a complete WP newbie
Anyhow, after learning that this cannot be done by default, I looked into the get_categories functions and finally came up with a solution
function category_custom_field_get_terms_orderby( $orderby, $args ){
if($args['orderby'] == 'category_custom_field' && isset($args['category_custom_field']))
return 'cv.field_value';
return $orderby;
}
function category_custom_field_get_terms_fields( $selects, $args ){
if($args['orderby'] == 'category_custom_field' && isset($args['category_custom_field']))
$selects[] = 'cv.*';
return $selects;
}
function category_custom_field_terms_clauses($pieces, $taxonomies, $args){
global $wpdb;
if($args['orderby'] == 'category_custom_field' && isset($args['category_custom_field']))
$pieces['join'] .= " LEFT JOIN $wpdb->prefix" . "ccf_Value cv ON cv.term_id = tt.term_id AND cv.field_name = '".$args['category_custom_field']."'";
return $pieces;
}
add_filter('get_terms_orderby', 'category_custom_field_get_terms_orderby',1,2);
add_filter('get_terms_fields', 'category_custom_field_get_terms_fields',1,2);
add_filter('terms_clauses', 'category_custom_field_terms_clauses',1,3);
(The code above can be put into the theme functions.php file)
then the code to get categories is:
get_categories('child_of=92&hide_empty=false&orderby=category_custom_field&category_custom_field=date&order=DESC');
Any correction is greatly appreciated!
You can also give the get_categories new meta and sort using usort.
$subcategories = get_categories();
foreach ($subcategories as $subcategory) {
$subcategory->your_meta_key = your_meta_value;
}
foreach ($subcategories as $subcategory) {
blah blah blah
}
function my_cmp($a, $b) {
if ($a->ordering == $b->ordering) {
return 0;
}
return ($a->ordering < $b->ordering) ? -1 : 1;
}
usort($subcategories, "my_cmp");

drupal get list of terms of a node

How to get list of terms of a node ( by node id) belongs to a particular vocabulary. Is there any drupal function ?
taxonomy_node_get_terms function.
http://api.drupal.org/api/function/taxonomy_node_get_terms/6
Or also:
taxonomy_node_get_terms_by_vocabulary
http://api.drupal.org/api/function/taxonomy_node_get_terms_by_vocabulary/6
I know there is api for getting list of vocabularies But i am nto sure, one api exist for gettign list of terms of vocabularies.
However, you can try this function. It will work.
function myutils_get_terms_by_vocabulary($vname, $tname = "") {
$sql = "select td.*
from term_data td
inner join vocabulary v on td.vid = v.vid
where v.name = '%s'";
if($tname) {
$result = db_query($sql . " and td.name = '%s'", $vname, $tname);
return db_fetch_object($result);
} else {
$result = db_query($sql, $vname);
}
$terms = array();
while ($term = db_fetch_object($result)) {
$terms[$term->tid] = strtolower($term->name);
}
return $terms;
}
Basically i created a 'myutils' module for such common functions and added this function there. so that i can use them in all similar scenarios.

Resources