I have some problem that, I am using criteria to customize a number column query
$criteria=new CDbCriteria();
$criteria->select =array('CompanyName', 'CompanyCountCoupon','CompanyDes', 'CompanyLogo');
$models = Company::model()->findAll($criteria);
After I put it to array and echo result
$rows = array();
foreach($models as $i=>$model1) {
$rows[$i] = $model1->attributes;
}
echo CJSON::encode($rows)
My problem is that the results contains all attributes of table, and attributes not in criteria->select will set = null
{"CompanyName":"abc","CompanyCountCoupon":"0","CompanyDes":"Hello","CompanyLogo":"\/upload\/company\/abc.jpg",**"CompanyID":null,"CompanyWebSite":null,"CompanyAdrress1":null,"CompanyAdrress2":null,"CompanyPhone1":null,"CompanyPhone2":null**}
Please help me.
Thanks to all
if you go with findAll() (using ActiveRecord) you won't be able to control that part, the way to go is a custom query :
$results = Yii::app()->db->createCommand()
->select('CompanyName ,CompanyCountCoupon ,CompanyDes ,CompanyLogo')
->from('company')
//->where() // where part
->queryAll();
echo CJSON::encode($results);
now its already good to be JSON encoded and also much faster than regular ActiveRecord
Use getAttributes()
Example
$rows = Company::model()->getAttributes(array('CompanyName','CompanyCountCoupon','CompanyDes', 'CompanyLogo'));
echo CJSON::encode($rows);
This is correct behaviour.
You are asking for specific columns, so this is being correctly provided.
Recall that the attributes is part of the model, not the query.
$model = Company::model()->findByPK();
print_r($model);
...
/* Company points to the TABLE. not the query */
class Company extends CActiveRecord
{
---
}
Related
The Context
I'm using Laravel's Eloquent as my ORM. I am creating an API endpoint which provides access to Cars which have several attributes (color, make, status).
My endpoint allows clients to filter the return value by any subset of those attributes, if they provide no attributes then I will return everything.
The Question
I want to build a conditional query, which starts from "all" and narrows down based on which parameters have been specified. Here's what I've written:
public function getCars(Request $request)
{
$results = Cars::all();
if($request->has('color'))
$results = $results->where('color', $request->input('color'));
if($request->has('make'))
$results = $results->where('make', $request->input('make'));
if($request->has('status'))
$results = $results->where('status', $request->input('status'));
return $results->toJson();
}
If I call this with no parameters the API returns a list of all cars in the database.
If, however, I specify (for instance) status of 0 the API returns an empty set, despite the fact that some cars have status of 0.
Am I approaching this incorrectly? Is there something fundamental I'm missing?
Note that if instead I write:
$results = Cars::where('status', 0);
return $results->get();
The list of cars is properly generated
You should change your function like this:
public function getCars(Request $request)
{
$results = Cars::query();
if($request->has('color'))
$results = $results->where('color', $request->input('color'));
if($request->has('make'))
$results = $results->where('make', $request->input('make'));
if($request->has('status'))
$results = $results->where('status', $request->input('status'));
return $results->get()->toJson();
}
You could try this, for simplicity.
$query = Cars::query(); // no query executed, just give us a builder
$query->where(array_only($request->all(), ['color', 'make', 'status'])); // where can take a key value array to use
// update: only taking the vars you need, never trust incoming data
return $query->get(); // will be converted to Json for you
This only queries the DB for what you need. Yours is returning all results then filtering through them in a collection.
Update:
As Joseph stated, there is different functionality between $request->only() and array_only. The functionality of array_only is wanted here.
I am new to cakephp. I have a problem with calling the function. here is my issue.
In Contrloller file i get all the values using the following function
public function index()
{
$conditions = array(
'order' => array('Histroy.chat_sk DESC')
);
$this->set('histroys', $this->Histroy->find('all',$conditions));
}
In My model file have the following,
class Histroy extends AppModel
{
public $tablePrefix = 'plc_';
public $useTable = 'chat_history';
}
In my view file i have listed the values using foreach() function and that as follows
foreach ($histroys as $histroy):
$oper_name = $histroy['Histroy']['operator_fk'];
$operator_email = $histroy['Histroy']['email'];
endforeach
in that opertaor_fk is a field in history table. So i need get the operator name by another table as operators. So i need to call that function in the view.
Ex : In core we can do like as,
$operator_name = operator_name($fetch['operator_id']);
Function should be like this:
function operator_name($id)
{
// Select the value for the matched field in the operator
return $operator_name;
}
In cakephp how can i retrieve the values.
Please help me out to fix this. Thanks in Advance
Follow the blog tutorial for cake. It'll explain how to create associations and relationships between tables to let you do what is is you want, but in a nutshell, you need to create a relationship between History and Operator models and work from there.
The "in" property used in Extbase does not seem to be working for me.
$actor contains an array of Actor model objects. My Movie model and Actor are in m:n relation.
I tried something like this in my Movie Repository:
$query=$this->createQuery();
$query->matching($query->in('actors',$actors));
$result = $query->execute()->toArray();
$result is showing NULL
I tried passing array of actor uids too but that wont work as well:
$query->matching($query->in('actors',[$actor_1_uid,$actor_2_uid]));
There is of course contains but using in should be more convenient.
I don't see any problem in your statement. Just to be clear, a "in" statement must be placed somewhere inside a matching statement, which is correct in your case.
However, you should change your create query for
$query = $this->createQuery();
instead of
$query=$this->create->query();
If you have still no result, I suggest you check the exact the SQL statement executed by extbase, there's a tricky way to do it in TYPO3.
You have to locate the following file in the core:/typo3/sysext/extbase/Classes/Persistence/Generic/Storage/Typo3DbBackend.php
locate the replacePlaceHolders function and add the following codes at the end of the function:
if (strpos( $sqlString, "my_table_name" ) !== false) {
echo $sqlString;
}
I will echo every statement that is being made for the following "my_table_name" table. Of course, never do that in your production server.
I hope it will help!
Cheers,
Olivier
Sorry, but $query->in is the wrong approach. AFAIK it will not work for m:n reations, only for 1:n.
Try something like this, $actors being a query result from the model or the actors repository:
$constraints = array();
foreach ($actors as $actor) {
$constraints[] = $query->contains('actors', $actor->getUid());
}
if (!empty($constraints)) {
$result = $query->matching($query->logicalOr($constraints))->execute();
}
Of course you can use your own array of uids for the loop, then just drop the getUid() method
I am fetching data from Articles table but I want to extend returned result with some data from another table.
For example:
public function getArticlesByCategoryId($category_id = 0) {
$select = $this->_db->select()
->from($this->_name)
->limit(5)
->order("pubDate DESC");
$result = $this->_db->fetchAll($select);
$mCategories = new Model_Categories();
foreach($result as $row) { // as &$row doesn't work
$category_name = $mCategories->getNameById($row["category_id"]);
$row["category_name"] = $category_name; // this to add to $result but dunno how
// blah blah...
}
return $result; // the new one with ...->category_name in it.
}
I hope you could understand what I am looking for.
Or maybe it is better to write a single query (with joins, don't know how) and fetch all the data needed in once without calling methods from another Models?
This indeed looks like you should use a join. This definitely is the easiest way to solve your problem. The following query would do the trick:
$select = $this->_db->select()
->from($this->_name)
->join('category_table', 'category_table.id = ' . $this->_name . '.category_id', array('category_name'))
->limit(5)
->order("pubDate DESC");
This will add the category name to the row.
In case you don't want to use a join, you can add a custom field to your row by using a custom row class. This however requires a bit more work. Create the class as follows:
class MyApp_Model_Row_MyRow extends Zend_Db_Table_Row_Abstract
{
public $categoryName;
}
Then you should indicate in your DbTable class that you want to use this new row class:
class MyApp_Model_DbTable_Articles extends Zend_Db_Table_Abstract
{
...
protected $_rowClass = 'MyApp_Model_Row_MyRow';
}
You can then set the category name in a fetched row.
To get all articles with data from your category table your query could look like:
$select = $this->_db->select()
->from($this->_name)
->joinLeftUsing('category','category_id', array('category_name'))
->order("pubDate DESC");
See also: http://framework.zend.com/manual/en/zend.db.select.html
I am working on my first module for magento version 1.3.2.3.
I have created a simple table (not EAV, just a primary key and 2 columns) and some classes to access it, following Alan Storm's articles which helped me a lot, but I can't figure out how to make a simple select: Alan explains how to load with the primary key, but not selecting rows that match some value.
In normal MySQL I'd write:
SELECT *
FROM my_table
WHERE some_field = '" . $someValue . "'
I've found a snippet which gives me the result I want:
$resource = new Mage_Core_Model_Resource();
$read = $resource->getConnection('core_read');
$select = $read->select()
->from('my_table')
->where('some_field = ?', $someValue);
return $read->fetchAll($select);
But there have to be an easier/prettier solution, using the model class I've created. The result will be a single row, not a collection.
I've tried everything I could think of, like:
return Mage::getModel('modulename/classname')->select()->where('some_field = ?', $comeValue);
return Mage::getModel('modulename/classname')->load()->where('some_field = ?', $comeValue);
return Mage::getModel('modulename/classname')->load(array('some_field = ?', $comeValue));
and more stuff, but no luck so far: what am I missing??
You probably want to use your model's Collection for that.
$collection = Mage::getModel('mygroup/mymodel')->getCollection();
$collection->addFieldToFilter('some_field',$some_value);
foreach($collection as $item)
{
var_dump($item);
}
var_dump($collection->getFirstItem());
var_dump($collection->getLastItem());
Here's an example of how this is achieved in the CoreUrlRewrite Model class:
public function loadByIdPath($path)
{
$this->setId(null)->load($path, 'id_path');
return $this;
}
You can create similar methods in your model classes. You can also use the alternative form of the load method anywhere in your code:
$model = Mage::getModel('modulename/classname')->load($someValue, 'some_field');