Write an update query where ID is X, and name is either foo or bar in zf - sql

I'd like to write the following SQL update query with Zend Framework:
UPDATE my_table
SET my_field
WHERE name = 'John'
AND (other_field = 'foo' OR other_field = 'bar')
How to do this with Zend Framework?

Assuming you have a Model file for my_table ..if not create one inside your model directory.
<?php
class Yournamespace_Model_Mytable extends Zend_Db_Table_Abstract{
protected $_name = "my_table";
public function updateFunction(){
$data = array('my_field' => 'new value to be set');
$where[] = 'name = John';
$where[] = '(other_field = "foo" OR other_field = "bar")';
$update= $this->update($data, $where);
}
}
just call in any action like this
$obj = new Yournamespace_Model_Mytable();
$obj->updateFunction();

Related

$queryBuilder->createNamedParameter in update query not working (TYPO3 10.4)

In a custom utility class (no controller or repository) I have the following UPDATE-Query:
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('my_table');
$uid = 1;
$val = 'Test';
$queryBuilder
->update('my_table')
->set('title', $queryBuilder->createNamedParameter($val))
->where(
$queryBuilder->expr()->eq('uid', $uid)
)
->execute();
When the update is done, the title in the database record has the value ":dcValue1" and not "Test".
Why does the prepared statement not resolve the parameter $val?

Magento 2: Get Product, Sku and Manufacturer name from database

I use this query to get Product Name and Sku.
I would to add "brand name" that is stored in Manufacturer attributes . Is it possible to expand this query to get manufacturer name by product?
SELECT nametable.value,
nametable.store_id,
m2_catalog_product_entity.sku
FROM `m2_catalog_product_entity_varchar` AS nametable
LEFT JOIN m2_catalog_product_entity
ON nametable.entity_id = m2_catalog_product_entity.entity_id
WHERE nametable.attribute_id = (SELECT attribute_id
FROM `m2_eav_attribute`
WHERE `entity_type_id` = 4 and store_id = 0
AND `attribute_code` LIKE 'name');
I would highly recommend leveraging Magento 2 product object for retrieving the information instead of building queries yourself.
Inside a php class you can retrieve it like this using factory method:
<?php
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Catalog\Model\ProductFactory $product
) {
$this->product = $product;
parent::__construct($context);
}
public function getProduct($id)
{
$product = $this->product->create()->load($entity_id);
$sku = $product->getSku(); // get SKU
$name = $product->getName(); // get name
$manufacturer = $product->getManufacturer(); // get manufacturer
}
}
Or via Object Manager
$entity_id = "your product id";
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->create('Magento\Catalog\Model\Product')->load($entity_id);
$sku = $product->getSku(); // get SKU
$name = $product->getName(); // get name
$manufacturer = $product->getManufacturer(); // get manufacturer
To retrieve any attribute you want, you can use
$attribute = $product->getData("attribute_code"); // get any attribute

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';

Entity Framework Update Statement

I'm trying to update a specific record based off of a users selection. Regarding Entity Framework syntax, I'm not very familiar. Is it possible to achieve this SQL statement in Entity FrameWork?
Thank you!
update Table1
set Colum1='1'
where Column2='1234567'
var record = _db.Table1.where(r => r.Column2 == '1234567');
record.Column1 = '1'
_db.SaveChanges();
where _db is the Entity Framework DbContext class...
HTH.
Yes, Linq Version:
Table1Entity entity = from e in dbContext.Table1Entitys
where e.Column2 = '1234567'
select e
entity.Column1 = '1';
dbContext.SaveChanges();
And looks like Sunny has the Lambda version.
However, neither this nor Sunny's answer produces the exact SQL because they both actually produce a SELECT and an UPDATE:
SELECT <all columns>
FROM <table>
WHERE Column2 = '1234567'
UPDATE <table>
SET <allcolumns> = <allvalues>, etc etc
WHERE Column2 = '1234567'
If you want to just an UPDATE, then you would do something like:
var row = new Row();
// assuming a single column PK (id)
row.Column1 = '1';
row.Column2 = '1234567';
dbContext.Attach(row);
var entity = dbContext.Entity(entity);
entity.Property(e => e.Column2).IsModified = true;
dbContext.SaveChanges();
produces exactly:
UPDATE <Table>
SET Column2 = '1234567'
WHERE Column1 = '1'
// Note: ctx = your DbContext
var tbl1 = (from t in ctx.Table1 where t.Id == 1234567 select t).FirstOrDefault();
if (tbl1 != null) {
tbl1.Column1 = "1";
ctx.SaveChanges();
}

Yii: adding custom fields

Is there a simple way of adding custom fields to a model? Say I have a table "user" with 3 fields: id, name and surname. I want this:
$user = User::model()->findByPk(1);
$echo $user->fullName; // echoes name and surname
Please note: I want this custom field to be added via sql, smth like
$c = new CDbCriteria();
$c->select = 'CONCAT("user".name, "user".surname) as fullName';
$user = User::model()->find($c);
Problem is that fullName property is not set.
UPD:
here is the code for a little bit trickier problem -- custom field from another table. This is how it's done:
$model = Application::model();
$model->getMetaData()->columns = array_merge($model->getMetaData()->columns, array('fullName' => 'CONCAT("u".name, "u".surname)'));
$c = new CDbCriteria();
$c->select = 'CONCAT("u".name, "u".surname) as fullName';
$c->join = ' left join "user" "u" on "t".responsible_manager_id = "u".id';
$model->getDbCriteria()->mergeWith($c);
foreach ($model->findAll() as $o) {
echo '<pre>';
print_r($o->fullName);
echo '</pre>';
}
You can add a function to the User class:
public function getFullName() { return $this->name.' '.$this->surname; }
This will return the full name as if it were an attribute from the database. This is much easier than adding a calculated column to the SQL.
In model
public function getMetaData(){
$data = parent::getMetaData();
$data->columns['fullName'] = array('name' => 'fullName');
return $data;
}
Thus not recommended