Yii: adding custom fields - yii

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

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++)

How to return a JSON array from sql table with PhalconPHP

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);
}

$data = $query->row(); returns only one row

Im trying to list the results of my sql query (picking up all the movies from a category), but I cannot figure out how to get all the rows instead of only one.
Here's the code :
$this->load->database();
$sql = 'SELECT * FROM movies WHERE category = "'.$movies_category.'";';
$query = $this->db->query($sql);
$data = $query->row();
$this->response($data, 200);
I've tried :
while($row = mysql_fetch_assoc($query)){
$data = $query->row();
}
$this->response($data, 200);
And it doesn't work. Any suggestion ? Thank you !
$this->load->database();
$sql = 'SELECT * FROM movies WHERE category = "'.$movies_category.'";';
$query = $this->db->query($sql);
$data = $query->result();
To traverse the $data array:
foreach($data AS $row)
{
//to retrieve the data from each row.
$col1 = $row->col1;
$col2 = $row->col2;
}
Use result() instead of row(). result() will return an array of objects that are your results. Alternatively, you can useresult_array() which will resturn an array of arrays keyed according to your columns. Please refer to here for a better outline of the result() and row() methods.
Do you have a database configuration file? the load->database() requires it. Where is $movies_category coming from? This will let you iterate over your results.
$this->load->database();
$sql = 'SELECT * FROM movies WHERE category = "'.$movies_category.'";';
$query = $this->db->query($sql);
foreach ($query->result() as $row)
{
echo $row->column;
}
Where column corresponds with one of the values in the movies table.
I'm surprised nobody has mentioned the potential hazards of using variables (possibly user input) in your SQL. You should seriously consider using query bindings or the active record features of CodeIgniter to build safer queries.
Consider the following solution to your problem:
$this->load->database();
$sql = 'SELECT * FROM movies WHERE category = ?';
$query = $this->db->query($sql, array($movies_category));
// $data = $query->result(); // returns result as an array of objects
$data = $query->result_array(); // returns result as array
$this->response($data, 200);
I'm assuming this is for some sort of API? If so, consider using the result_array() method as it will probably be better suited for your needed output, and also really easy to convert into JSON:
$json_data = json_encode($data);
Hope that helps,
Cheers.
For your question row() return only one value its good for checking in ID and if you want get all the rows use result_array() or simple result()
You can try this code....
Model:
function get_movies($movies_category){
$this->db->where("category",$movies_category);
$query = $this->db->get("movies");
return $query->result_array();
}
Controller:
$this->data['movies'] = $this->'name of model'->get_movies('here is the movie categories');
View:
foreach($movies as $m){
print_r($m);
}
exit();
Note you can directly add the code in function in model to controller add this in your controller if you want directly...
$this->data['movies] = $this->db->get('movies')->result_array();

yii, how to select one column from model

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.

How do I select and display a specific field from may table in cakephp?

I have this code in my products_controller.php:
<?php
class ProductsController extends AppController{
var $name = 'Products';
var $helpers = array('Form');
//var $scaffold;
function index(){
$this->Product->recursive = 1;
$products = $this->Product->find('all');
$this->set('products',$products);
//pr($products);
}
function add(){
if(!empty($this->data)){
$this->Product->create();
$this->Product->save($this->data);
$this->redirect(array('action'=>'index'));
}
$categories = $this->Product->Category->find('list',array(
'field'=>array('Category.categoryName')
));
$this->set('categories',$categories);
pr($categories);
}
}
?>
what it actually does in my database is this:
SELECT `Category`.`id` FROM `categories` AS `Category` WHERE 1 = 1
The thing is, I am not trying to select Category.id. I want to select Category.categoryName which is another field in my database so that it will automatically populate a dropdown list in my add.ctp file which goes like this:
<h2>ADD</h2>
<?php echo $form->create('Product'); ?>
<?php
echo $form->input('ProductName');
echo $form->input('categories');
echo $form->end('DONE');
?>
any help would be highly appreciated.
In your Category Model set the displayField Name property with the Category Name.
public $displayField = 'categoryName';