Incorrect usage of UPDATE and ORDER BY In Laravel eloquent - sql

Iam trying to update 'sortOrder' column based on a given list of ids.
For example, if the given IDs are:
$orderList = ['id' =>'1','id' =>'5','id' =>'3']
ID of '1' => 'sortOrder column' = 1
ID of '5' => 'sortOrder column' = 2
ID of '3' => 'sortOrder column' = 3
Query statement:
$ids_array = array_pluck($orderList, 'id');
$ids_string = implode(',', $ids_array);
DB::statement(DB::raw('set #rownum=0'));
$result = DB::table('requirements')
->join('sections', 'sections.id', '=', 'requirements.section_id')
->whereIn('id', $ids_array)
->orderByRaw("FIELD(requirements.id, {$ids_string})")
->update([
'requirements.sortOrder' => DB::raw('#rownum := #rownum + 1'),
]);
But when I try to update using this query, I am getting an error:
SQLSTATE[HY000]: General error: 1221 Incorrect usage of UPDATE and ORDER BY

Related

SELECT DISTINCT ON expressions must match initial ORDER BY expressions in typeorm query

I have a query that I want get rows with unique item_id and sort them according to timestamp.
But I get this error everytime from this code
const boxPreviewActivities = await this.activityLogEntryRepository
.createQueryBuilder('activityLogEntry')
.where("activityLogEntry.activity = 'BOX_PREVIEW'")
.andWhere('activityLogEntry.projectId = :projectId', { projectId })
.andWhere('activityLogEntry.userSub = :userSub', { userSub: user?.sub })
.andWhere((qb) => {
const subQuery = qb
.subQuery()
.select(
"DISTINCT activityLogEntry.originalData ::jsonb -> 'source' ->> 'item_id'"
)
.from(ActivityLogEntryEntity, 'activityLogEntry')
.where("activityLogEntry.activity = 'BOX_DELETE'")
.getQuery();
return `activityLogEntry.originalData ::jsonb -> 'source' ->> 'item_id' NOT IN (${subQuery})`;
})
.distinctOn([
"activityLogEntry.originalData ::jsonb -> 'source' ->> 'item_id' ",
])
.orderBy('activityLogEntry.timestamp', 'DESC')
.limit(limitNumber)
.getMany();
return boxPreviewActivities;
}
** ERROR [ExceptionsHandler] SELECT DISTINCT ON expressions must match initial ORDER BY expressions
QueryFailedError: SELECT DISTINCT ON expressions must match initial ORDER BY expressions**
if I add this two order functions at the and, I dont get error but my query not sorting according to timestamp, instead sort only with item_id. Actually I only want to sort according to timestamp. How can I refactor my query to make it working ?
.orderBy(
"activityLogEntry.originalData ::jsonb -> 'source' ->> 'item_id'",
'DESC'
)
.addOrderBy('activityLogEntry.timestamp', 'DESC')

How to do `UPDATE...SET...FROM` using knex?

What's the most terse way I can express an UPDATE...SET...FROM SQL statement using knex? This is what I've got currently:
const query =
knex('user_subscriptions').update(subscription).toQuery() +
knex.raw(
' from plans p where customer_id = ? and p.id = us.plan_id ' +
'returning us.*, p.name',
[customer_id]
);
The reason I'm doing this is that I want to efficiently return a field from a related table (JOIN style) without needing a separate query.
As instructed in the official site: knexjs.org/#Builder-update
knex('user_subscriptions')
.returning(['us.*', 'plans.name', 'customer_id'])
.where({
customer_id: '?',
plans.id: us.plan_id
})
.update({
subscription : '?
})
Does:
update `user_subscriptions` set `subscription ` = '?' where `customer_id` = '?' and 'plans.id' = 'us.plan_id'
Returns:
[ us.*: ..., plans.name: ..., customer_id: ... ]

Magento - SQL - Select all products by attribute and update it

I need to select all products with specific attribute (barcolor) and then update attribute with another value.
EXAMPLE.
I would like to select all SKU with barcolor = LIGHT GREEN and update them to GREEN.
Thanks!
you can do this from backend. you can go to catalog > manage products > select all products > at the right side you can see update attributes option , select that and click on submit and you will redirect to another page and than give the value in required field and save it.
It can be achieve by programming also.
If you have attribute option ID than:
$sAttributeName = 'brands';
$mOptionValueId = 250; // 250 is Id of Brand 1
$newOptionValueId = 255; // 255 is Id of Brand 2
$productsCollection = Mage::getModel('catalog/product')->getCollection()
->addAttributeToSelect('*')
->addFieldToFilter(
$sAttributeName,
array(
'eq' => $mOptionValueId
)
);
$storeId = Mage::app()->getStore()->getStoreId();
foreach($productsCollection as $product) {
$productId = $product->getId();
Mage::getSingleton('catalog/product_action')->updateAttributes(
array($productId),
array('brands' => $newOptionValueId),
$storeId
);
}
If you do not have attribute option ID than you can use the option value directly as:
$sAttributeName = 'brands';
$mOptionValue = 'Brand 1';
$newOptionValue = 'Brand 2';
$productsCollection = Mage::getModel('catalog/product')->getCollection()
->addAttributeToSelect('*')
->addFieldToFilter(
$sAttributeName,
array(
'eq' => Mage::getResourceModel('catalog/product')
->getAttribute($sAttributeName)
->getSource()
->getOptionId($mOptionValue)
)
);
$storeId = Mage::app()->getStore()->getStoreId();
foreach($productsCollection as $product) {
$productId = $product->getId();
Mage::getSingleton('catalog/product_action')->updateAttributes(
array($productId),
array('brands' => Mage::getResourceModel('catalog/product')
->getAttribute($sAttributeName)
->getSource()
->getOptionId($newOptionValue)),
$storeId
);
}
If you have the list of the entity_ids for all the products and you are using a custom attribute, you can run an SQL query for each and every product like so:
UPDATE `catalog_product_entity_varchar` SET value = 'NEW BLACK' WHERE entity_id = '12345' AND attribute_id = 'attribute_id_here';
You can also filter the fields by:
SELECT entity_id,value FROM catalog_product_entity_varchar WHERE value LIKE 'something';

Conditions in JOINed tables shows error CakePHP

I have two tables employee_personals where all the personal record of the employee is stored and telephone_bills where the telephone bills paid to a particular employee is stored for each month. Now in my employeePersonalsController.php I have a function called api_show_employees() which is similar to below :
function api_show_employees() {
//$this->autoRender = false;
//Configure::write("debug",0);
$office_id = '';
$cond = '';
if(isset($_GET['office_id']) && trim($_GET['office_id']) != '') {
$office_id = $_GET['office_id'];
$cond['EmployeePersonal.office_id'] = $office_id;
}
if(isset($_GET['telephoneBillTo']) && isset($_GET['telephoneBillFrom']) ) {
if($_GET['telephoneBillTo'] != '' && $_GET['telephoneBillFrom'] != '') {
$cond['TelephoneBill.bill_from'] = $_GET['telephoneBillFrom'];
$cond['TelephoneBill.bill_to'] = $_GET['telephoneBillTo'];
}
}
$order = 'EmployeePersonal.name';
// $employee = $this->EmployeePersonal->find('all');
$employee = $this->EmployeePersonal->find('all',array('order' => $order,'conditions'=>$cond));
//return json_encode($employee);
}
This functions basically finds all the employees who paid bills in the given period. But I am getting an error
Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'TelephoneBill.bill_from' in 'where clause'
Models : EmployeePersonal.php:
var $hasMany = array(
'TelephoneBill' => array(
'className' => 'TelephoneBill',
)
);
TelephoneBill.php
public $name = 'TelephoneBill';
var $hasMany = array('EmployeePersonal');
NB: If I skip the bill_from and bill_to conditions, I am getting the results , with TelephoneBill array !
TLDR: use Joins instead.
Details/Notes:
1) it looks like you're using recursive. Don't do that. Use Containable instead.
2) You can't limit the parent model based on conditions against data from a contained/recursive-included table - instead, use Joins.
2b) Or, you could query from the other direction, and query your TelephoneBill with conditions, then contain the EmployeePersonal.

Zend_Db problem whith the placeholders from SQL string

I have the following SQL
SELECT i_id AS "entity_id", "entity_1" AS "type"
FROM tbl_extensions WHERE ext = 50
which returns me the result and an additional column "type" with the value "entity_1"
to gain the same with Zend_Db I've tried:
$db->fetchAll($db->select()
->from('tbl_extensions',
array('entity_id' => 'i_id',
'type' => 'entity_1'))
->where('ext = ?', 50)));
But I have the following error:
Message: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'tbl_extensions.type' in 'field list'
It looks like Zend tries to find a column instead of creating it within the result.
Could anyone help me with it?
easiest solution would be to use Zend_Db_Expr.
$db->fetchAll($db->select()
->from('tbl_extensions',
array(
'entity_id' => 'i_id',
new Zend_Db_Expr('"entity_1" AS "type"'),
)
)
->where('ext = ?', 50));