How can i convert the following to yii2
$dependency = new CDbCacheDependency('SELECT count(*) FROM job_title');
$jobTitle = JobTitle ::model()->cache(CACHE_TIMEOUT,$dependency)->findAll($array);
$jobTitleList = CHtml::listData($jobTitle, 'job_title_id','desc');
return $jobTitleList;
I have the following code which does not work.
use yii\db\ActiveRecord;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
$items = array();
foreach (Jobsprocess::find()->where($array)->all() as $value) {
$items[$value->process_id] = $value->jobsprocess;
}
return $items;
If I understand your question correctly, you need the following code in Yii 2 format.
Yii 1:
$dependency = new CDbCacheDependency('SELECT count(*) FROM job_title');
$jobTitle = JobTitle ::model()->cache(CACHE_TIMEOUT,$dependency)->findAll($array);
$jobTitleList = CHtml::listData($jobTitle, 'job_title_id','desc');
return $jobTitleList;
Yii 2:
use yii\helpers\ArrayHelper;
use app\models\JobTitle;
$jobTitleList = ArrayHelper::map(JobTitle::find()->where($array)->all(), 'job_title_id','desc');
return $jobTitleList;
But I don't know what are you doing with Jobsprocess model in the Yii 2 code. Because, In the Yii 1 format you haven't used that model.
Replacement for CHtml::listData in Yii 2 is ArrayHelper::map() Example:
$jobTitleList = ArrayHelper::map($jobTitle, 'job_title_id', 'desc');
Read more in official docs.
Related
I have several tables that have JSON arrays stored within fields.
Using PHP PDO I am able to retrieve this data without issue using:
$query1 = $database->prepare("SELECT * FROM module_settings
WHERE project_token = ? AND module_id = ? ORDER BY id DESC LIMIT 1");
$query1->execute(array($page["project_token"], 2));
$idx = $query1->fetch(PDO::FETCH_ASSOC);
$idx["settings"] = json_decode($idx["settings"]);
This returns a string like:
{"mid":"","module_id":"1","force_reg_enable":"1","force_reg_page_delay":"2"}
Attempting to gather the same data via PhalconPHP
$result = Modulesettings::findFirst( array(
'conditions' => 'project_token = "' . $token . '"' ,
'columns' => 'settings'
) );
var_dump($result);
Provides a result of
object(Phalcon\Mvc\Model\Row)#61 (1) { ["settings"]=> string(167) "{"text":"<\/a>
<\/a>
","class":""}" }
What do I need to do different in Phalcon to return the string as it is stored in the table?
Thank you.
You have 2 approach
First :
Get the settings with this structure :
$settings = $result->settings;
var_dump($settings);
Second :
First get array from resultset, then using the array element :
$res = $result->toArray();
var_dump($res['settings']);
Try it.
You can decode json right in your Modulesettings model declaration:
// handling result
function afterFetch() {
$this->settings = json_decode($this->settings);
}
// saving. Can use beforeCreate+beforeSave+beforeUpdate
// or write a Json filter.
function beforeValidation() {
$this->settings = json_encode($this->settings);
}
I'm building a custom module and i'm trying get all orders with specific status:
$canceledQuery = Mage::getSingleton('core/resource')->getConnection('core_read')->select()
->from('mage_sales_flat_order', 'entity_id')
->where('status = ?', 'canceled');
This works very well. But now i'm trying use OR in where, without success.
I have been try this:
$whereCanceled = array();
foreach ($_status as $statusCode => $value) {
$whereCanceled[] = sprintf('%s=:%s', 'status', $statusCode);
}
$ordersQuery = Mage::getSingleton('core/resource')->getConnection('core_read')->select()
->from('mage_sales_flat_order', 'entity_id')
->where(implode(' OR ', $whereCanceled));
So, I don't know how use OR right in this case. I found no use for this with OR. Any idea?
instead of implode use join. magento use join itself.
->where(join(' OR ', $orWhere));//$orWhere array of condition
you can see in below function magento use join for OR condition in where clause
public function getSystemConfigByPathsAndTemplateId($paths, $templateId)
{
$orWhere = array();
$pathesCounter = 1;
$bind = array();
foreach ($paths as $path) {
$pathAlias = 'path_' . $pathesCounter;
$orWhere[] = 'path = :' . $pathAlias;
$bind[$pathAlias] = $path;
$pathesCounter++;
}
$bind['template_id'] = $templateId;
$select = $this->_getReadAdapter()->select()
->from($this->getTable('core/config_data'), array('scope', 'scope_id', 'path'))
->where('value LIKE :template_id')
->where(join(' OR ', $orWhere));
return $this->_getReadAdapter()->fetchAll($select, $bind);
}
for more reference open file located at [magento]/app/code/core/Mage/Core/Model/Resource/Email/Template.php
Hope this help you
I have set up model with gii and I have table call make and it has a few columns, there is one that is called make, how can I get all the data from column make back in the controller.
here is my action
public function actionAutoCompleteMake()
{
$makeModel= Make::model()->load(fieldMake);
}
If you're new to Yii, you should check out the docs for Yii's Active Record.
public function actionAutoCompleteMake()
{
$makeModels = Make::model()->findAll(array("select"=>"fieldMake", "order"=>"fieldMake DESC"));
}
You can do this also with some condition :-
$criteria = new CDbCriteria;
$criteria->select = "fieldMake";
$criteria->condition = " fieldName = fieldValue";
$results = Make::model()->findAll($criteria);
May be It will help you also.
I have a problem with Yii's CDBCrtieria builder. I am trying to make a rather complex query while using the escaping and safe functions provided by PDO.
Here is the query I am basically trying to build:
SELECT * FROM tbl_audit_log
WHERE (model_id = 1 AND model = "Title") OR
(model_id = 1 AND model = "Product") //etc
This is being built dynamically in PHP like:
$model_ids = array(array($model->id, 'Title'));
foreach($model->products as $id => $product){
$model_ids[][] = $product->id;
$model_ids[][] = "Product";
}
So I don't know the values of the WHERE before I build the query. I must find an easy way to build:
WHERE (model_id = 1 AND model = "Title") OR
(model_id = 1 AND model = "Product") //etc
Dynamically.
I have looked through the documentation but the closest thing I see is addCondition which would require complex coding to get working properly.
Does Yii provide any easy way of achieving this without having to deal with writing complex code to name my params etc?
It is indeed a bit more complex, but here's a working solution:
$criteria = new CDbCriteria();
$param_id = 0;
// $model_ids is the one you built in your original code
foreach( $model_ids as $id_pair ) {
$criteria->addCondition( '( model_id = :id' . $param_id . ' AND model = :model' . $param_id . ' )', 'OR' );
$criteria->params[ ':id' . $param_id ] = $id_pair[0];
$criteria->params[ ':model' . $param_id ] = $id_pair[1];
$param_id++;
}
This will generate custom identifiers for each of your parameters so they will all be validated. Then you can just use $criteria in your query.
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