yii, how to select one column from model - yii

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.

Related

update some rows in code igniter

i'm new to codeigniter.
i need some help to update some rows.
here is my model:
public function change()
{
$aa = $this->input->post('id');
$bb = $this->input->post('app');
$query = $this->db->query('select kodeunit from user where email = "hehe#gmail.com"');
foreach ($query->result() as $row)
{
$kode = $row->kodeunit;
}
for($i=0;$i<sizeof($aa);$i++)
{
$data = array(
'approval' => $bb[$i]
);
$this->db->where('id_team', $aa[$i]);
$this->db->where('kodeunit', $kode);
$this->db->update('detail_tim', $data);
}
}
when i tried to update only one row, it worked with this way. but when im trying to update some rows, it doesnt change at all.
please help me to fix this problem thanks
Don't use sizeof() in your for loop, instead use $aa directly if it's an integer or count($aa) if it's an array
for($i=0;$i<count($aa);$i++)
it'll be better if you make it to other variable
$max = count($aa);
for($i=0;$i<$max;$i++)

yii2 listdata convert from yii1.x

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.

Yii left join query

I want to execute the below sql query using Yii framework and need help on this.
SQL query
SELECT t.*, LP.name AS lp_name FROM `user` AS `t` LEFT JOIN `level_profiles` AS `LP` ON t.prof_i = LP.id WHERE t.bld_i IN (17)
So, i tried the below steps.
$usql = 't.bld_i IN (17)';
$criteria1 = new CDbCriteria;
$criteria1->select = 't.*, LP.*';
$criteria1->join = ' LEFT JOIN `level_profiles` AS `LP` ON t.prof_i = LP.id';
$criteria1->addCondition($usql);
$criteria1->order = 't.prof_i';
$result = User::model()->findAll($criteria1);
The above step is not allowing me to access the value from 'level_profiles' table.
Then, i tried to execute:
$usql = 't.bld_i IN (17)';
$result = User::model()->with('level_profiles', array(
'level_profiles'=>array(
'select'=>'name',
'joinType'=>'LEFT JOIN',
'condition'=>'level_profiles.id="prof_i"',
),
))->findAll($usql);
This is returning an error 'Relation "level_profiles" is not defined in active record class "User". '
I know this could be executed using the below method.
Yii::app()->db->createCommand('SELECT query')->queryAll();
But i dont want to use the above.
I am a beginner with Yii and tried to look into the forums. But, i am getting confused how to execute the query using "User::model()" approach .
class User extends CActiveRecord
{
......
public function relations()
{
return array(
'level_porfile_relation'=>array(self::BELONGS_TO, 'Level_Profiles_Modelname', 'prof_i'),
);
}
and your query will be:
$result = User::model()->with('level_porfile_relation')->findAll($usql);

Preserve Order of IN in ORM Order

I'm trying to do a query where I preserve the order of the ids in a IN statement. I can't seem to do it with either the Model Manage Query Builder or the standard ORM 'order' array parameter. Am I missing something? I keep getting:
UNEXPECTED TOKEN IDENTIFIER(, NEAR TO 'id`enter code here`,17743,16688,16650
Here's my model manager:
$query = $this->modelsManager->createQuery('SELECT * FROM Projects WHERE id IN ('.implode(',', array_keys($finalIterations)).')
ORDER BY FIELD(id,'.implode(',', array_keys($finalIterations)).'');
It's pretty obvious PhQL doesn't like the FIELD key word. Is there a way for me to do what I'm trying to do with PhQL? It seems I will not be able to do what I need to.
Unfortunately as previously said, this is missing a feature in Phalcon.
Have a look at this function, I've put it into my ModelBase abstract class which is parent class of all my models. It uses PhQL variable binding, so it's safe for handling direct user input.
You could have reimplemented custom \Phalcon\Mvc\Model\Criteria but this solution seems to be easier to work with, at least for me.
ModelBase abstract
public function appendCustomOrder( \Phalcon\Mvc\Model\CriteriaInterface &$criteria, $orderField, array &$orderValues = [] ) {
if(!empty($orderValues)) {
$queryKeys = $bindParams = [];
foreach($orderValues as $key => $id) {
$queryKey = 'pho'.$key;
$queryKeys[] = ':'.$queryKey.':';
$bindParams[$queryKey] = $id;
}
// TODO: add support for multiple orderBy fields
$criteria->orderBy('FIELD('.$orderField.','.implode(',',$queryKeys).')');
// there's no 'addBind' function, need to merge old parameters with new ones
$criteria->bind( array_merge( (array) #$criteria->getParams()['bind'], $bindParams ) );
}
}
Controller usage
$projectIDs = [17743, 16688, 16650];
$projectsModel = new Projects();
$criteria = $projectsModel->query->inWhere( 'id', $projectIDs );
$projectsModel->appendCustomOrder( $criteria, 'id', $projectIDs );
$projectsData = $criteria->execute();
This will generate valid PhQL syntax similar to this one:
SELECT `projects`.`id` AS `id`, `projects`.`title` AS `title`
FROM `projects`
WHERE `projects`.`id` IN (:phi0, :phi1, :phi2)
ORDER BY FIELD(`projects`.`id`, :pho0, :pho1, :pho2)

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