How to findAll with specific column with order by desc ?
Code bellow worked and find all from the developer id
$id = Yii::app()->user->getState('id');
$models = Games::model()->findAll('developer_id='.$id);
Code bellow worked and ordered
$models = Games::model()->findAll(array('order'=>'status'));
When I mixed together then only worked for findAll developer_id='.$id doesn't order by
$id = Yii::app()->user->getState('id');
$models = Games::model()->findAll('developer_id='.$id,array('order'=>'status'));
Any suggestion to do that ? Thanks
In your model, add this function:
public function scopes() {
return array(
'bystatus' => array('order' => 'status DESC'),
);
}
Now you can do the query like this:
$models = Games::model()->bystatus()->findAll('developer_id='.$id);
=====
Bonus: You can also add this function in your model:
public function bydeveloper($devId) {
$this->getDbCriteria()->mergeWith(array(
'condition' => 'developer_id = '.$devId,
));
return $this;
}
Now you can do the query like this:
$models = Games::model()->bystatus()->bydeveloper($id)->findAll();
you can try this -
$id = Yii::app()->user->getState('id');
$model = Games::model()->findAll(array("condition" => "developer_id = '".$id."'","order" => "status"));
its should be work
You can try use criteria:
$id = Yii::app()->user->getState('id');
$criteria=new CDbCriteria;
$criteria->compare('developer_id',$id);
$criteria->order='status DESC';
$models = Games::model()->findAll($criteria);
It's not the best way but you can do:
$models = Games::model()->findAll('developer_id='.$id.' order by status DESC');
Model::find()->where([['attribute'=>'value']])->orderBy(['attribute'=>SORT_DESC])->all();
Related
Is that possible to use variable in the onCondition?
Here is the relation:
public function getMybook()
{
return $this->hasOne(Book::className(), ['book_id' => 'idbook'])->onCondition(['user_id' => $user_id]);
}
I want to use it in joinWith like below:
$books = Books::find()->joinWith('myBook')->all();
But how do I send the user_id parameter into the onConditon? Thanks!
You may use closure, for example:
return $this->hasOne(Book::className(), ['book_id' => 'idbook'])->andWhere('user_id = :user_id');
$user_id = 123;
$books = Books::find()->joinWith([
'myBook' => function ($q) use ($user_id) {
$q->addParams([':user_id' => $user_id]);
}
])->all();
Can not use dynamic param in relation function.
But why don't you use where condition:
$books = Books::find()->joinWith('myBook')->where(['myBook.user_id'=>$user_id])->all();
$model = new TableName('search');
$criteria = new CDbCriteria;
$criteria->order = 'id DESC';
$model = $model->findAll($criteria);
$model->unsetAttributes(); // clear any default values
if (isset($_GET['TableName']))
$model->attributes = $_GET['TableName'];
$this->render('TableNameView', array(
'model' => $model,
));
after use this code gets a white screen, no any action, and it should sort the why this is happening and how can I fix this way?
You override the original value of $model variable.
$model = $model->findAll($criteria);
After that $model is not an instance of TableName anymore! findAll returns a list of TableName's. So, you must iterate throught this list to get a single instance of TableName.
$models = $model->findAll($criteria);
foreach( $models as $model ) {
// do something with $model
}
Or, if you just need to get the last record, you can use find:
$criteria = new CDbCriteria;
$criteria->order = 'id DESC';
$model = $model->find($criteria);
I want to make a relation table in table pelatih and table absen. But when I try to make a relation id_pelatih it always input number "3".
This is the controller:
function absen()
{
$this->load->library('user_agent');
$nim = $this->uri->segment(4);
$id_user = $this->session->userdata('user_id');
$id_pelatih = $id_pelatih;
$this->load->model('mabsensi');
$data = array(
'id_pelatih' => $this->mlogin->get_data_pelatih_by_id_user($id_user)->id_pelatih,
'nim' => $nim,
'tanggal' => date('Y-m-d H:i:s'),
'keterangan' => 'Hadir'
);
$this->mabsensi->insert_absensi($data);
redirect($this->agent->referrer());
}
This is the model
function get_data_pelatih_by_id_user($id_user)
{
$this->db->select('*')
->from('pelatih as a, user as u')
->where('a.id_user = u.id_user')
->limit(1);
return $this->db->get()->row();
}
Please tell me how to solved this.
Your model isn't correct. If you want to get data from different tables you should use JOIN. And you have to say which record you need. So, add a WHERE statement to your query.
function get_data_pelatih_by_id_user($id_user)
{
$this->db->SELECT('*')
->FROM('user')
->WHERE('id_user', $id_user) // your parameter, you did not use it
->JOIN('pelatih', 'pelatih.id_user = user.id_user');
return $this->db->get();
}
Also have a look at the documentation: http://ellislab.com/codeigniter/user-guide/database/active_record.html
Hi I am new to yii and I am currently working on a project and I am having trouble with CDbCriteria.
My target query is:
title LIKE '$_GET['search']%' OR description LIKE '$_GET['search']%'
Is it possible to attain same result like this using CDbCriteria compare?
Controller action :
public function actionClassifieds(){
$model = new Classifieds('search');
$model->unsetAttributes();
if(isset($_GET['category'])){
if( $_GET['category'] == 0 ){
$model->classified_category_id = '';
}else{
$model->classified_category_id = $_GET['category'];
}
}
if(isset($_GET['search'])){
$model->title = $_GET['search'];
$model->description = $_GET['search'];
}
$this->render('classifieds',array('model'=>$model));
}
My model:
public function search()
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('classified_category_id',$this->classified_category_id);
$criteria->compare('title',$this->title,true);
$criteria->compare('description',$this->description,true);
$criteria->compare('price',$this->price,true);
$criteria->compare('timestamp',$this->timestamp);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
'pagination'=>array(
'pageSize'=>10,
),
));
}
Try:
$criteria->condition = "title LIKE :t OR description LIKE :d";
$criteria->params = array(
':t' => trim( Yii::app()->request->getParam('search') ).'%',
':d' => trim( Yii::app()->request->getParam('search') ).'%');
Better using Yii::app()->request->getParam($var_name)
UPDATED
$criteria->compare('classified_category_id',$this->classified_category_id);
$criteria->compare('price',$this->price,true);
$criteria->compare('timestamp',$this->timestamp);
$criteria->addCondition("title LIKE :t OR description LIKE :d");
$criteria->params[':t'] = $this->title;
$criteria->params[':d'] = $this->description;
i am trying to implement Pagination Using ZF2 and Doctrine.
What i am trying to do here is to fetch data from An associated table lets say 'xyz'.
Where as my categories table is doing one to many self referencing on its own PK.
MY catgories tables has following feilds
ID (PK)
Created_at
Category_id (self referencing PK)
My XYZ table lets say it is called Name table has
ID (PK)
Category_id(FK)
name
Detail
This is what i am trying to do to fetch data
public function allSubcategories($id, $column, $order) {
$repository = $this->entityManager->getRepository('Category\Entity\Category');
$queryBuilder = $repository->createQueryBuilder('category');
$queryBuilder->distinct();
$queryBuilder->select('category');
$queryBuilder->join('Category\Entity\CategoryName', 'category_name', 'WITH', 'category.id = category_name.category');
$queryBuilder->orderBy("category.status");
$q = $queryBuilder->getDql();
return $query = $this->entityManager->createQuery($q);
}
And in my controller this is what i am doing
public function subcategoryAction() {
///////////////////////////InPut Params Given for the pagination
$category_id = (int) $this->params()->fromRoute('id', 0);
$page = (int) $this->params()->fromRoute('page', 0);
$column = $this->params()->fromQuery('column');
$order = $this->params()->fromQuery('order');
$categoryModel = $this->getServiceLocator()->get('Category');
$categoryModel->category = $category_id;
$perPage = 10;
$request = $this->getRequest();
if ($request->isGet()) {
$view = new ViewModel();
$query = $categoryModel->allSubcategories($category_id, $column, $order);
$paginator = new ORMPaginator($query);
$paginator = new \Zend\Paginator\Paginator(new
\Zend\Paginator\Adapter\ArrayAdapter(array($paginator)));
$paginator->setCurrentPageNumber($page);
$paginator->setItemCountPerPage(2);
}
return array('id' => $category_id, 'view' => $paginator);
}
Now i am not getting results with pagination implemented can some 1 guide me about what i am missing?
You are using the wrong paginator there. Instead, you can use the one by DoctrineORMModule ( see DoctrineORMModule\Paginator\Adapter\DoctrinePaginator).
It may not be very obvious, but the logic is similar to what you already wrote:
use DoctrineORMModule\Paginator\Adapter\DoctrinePaginator as PaginatorAdapter;
use Doctrine\ORM\Tools\Pagination\Paginator as ORMPaginator;
use Zend\Paginator\Paginator as ZendPaginator;
$query = $categoryModel->allSubcategories($category_id, $column, $order);
$paginator = new ZendPaginator(new PaginatorAdapter(new ORMPaginator($query)));