I'm trying to personalize a symfony 2.4 repository query to retrieve only some fields. Everything is ok with flat fields but when retrieving Entity fields, I only get the id (by default) but not the whole entity data. My query:
$select = $this->createQueryBuilder('ca')
->select('ca.id, ca.name')
->leftJoin('ca.users', 'user')
->addSelect('(user) as users');
$select->setMaxResults($count);
return $select->getQuery()->getResult();
The result is: [{id: 1, name: "Some name", users: 1}, ...]
How can I change this query for users to contain the whole user data, like id, name, address, etc.?
This works for me:
$select = $this->createQueryBuilder('ca')
->select('partial ca.{id, name}, users')
->leftJoin('ca.users', 'users');
$select->setMaxResults($count);
return $select->getQuery()->getArrayResult();
You should try this way. You can use Partial.
$select = $this->createQueryBuilder('ca')
->select('partial ca.{id, name}')
->leftJoin('ca.users', 'users')
->addSelect('users');
A detailed description of this issue is available here. Doctrine2: Cannot select entity through identification variables without choosing at least one root entity alias
change this:
->select('ca.id, ca.name')
to this:
->select('ca')
i hope this will useful for you.
$qb = $this->em->createQueryBuilder();
$qb->select('o.id as order_id,o.createdBy as created_by,o.user as user_id');
// for getting selective fields
//$qb->select('o');
//for getting all fields in certain table
$qb->from('Entity\Orders', 'o');
$qb->setMaxResults(1);
// for getting single record only.
return $qb->getQuery()->getOneOrNullResult();
// for getting single record or null record.
//return $qb->getQuery()->getResult();
// for getting multiple records.
feel free to ask any query regarding it.
Related
I've been sitting for hours trying to find how to get values from table's iab_categories column category_name. I've found only the way to echo all table names:
$connection = Yii::app()->db;//get connection
$dbSchema = $connection->schema;
//or $connection->getSchema();
$tableNames = $dbSchema->getTableNames();//returns array of tbl schema's
var_export($tableNames);
Can anyone help me?
You can use query builder to do that:
$categories = (new \yii\db\Query())
->select(['category_name'])
->from('iab_categories')
->column();
The select() method sets what columns should be included in result.
The from() method sets what table should be queried.
And the column() method executes the query and return first column from result set as array.
EDIT: now, I've realized that even though you've mentioned Yii 2 in title the code you've included in question looks more like Yii 1.x.
So there is query builder version for Yii 1.x:
$categories = Yii::app()->db->createCommand()
->select('category_name')
->from('iab_categories')
->queryColumn();
I've been trying this query
Model::find()
->innerJoin('TranslationTable', 'TranslationTable.model_id = Model.id')
->where(['IN', 'translation_code', $arrayOfTranslationCodes])
->asArray()
->all();
The translation table contains multiple rows with the same ID but with different translation codes.
This query only returns the first matching locale for a given ID. How would I retrieve the other translation codes for a given ID?
This is the solution that I came to:
$query = Model::find()
-> innerJoin('TranslationTable', 'TranslationTable.model_id = Model.id');
foreach ($arrayOfTranslationCodes as $translation)
{
$query->andWhere(['OR', 'translation_code', $translation])
}
$queryResponse = $query->asArray()->all();
This allowed me to find rows with the same id, but have different translations. You need to store the $query->asArray()->all(); as $query itself just returns the active query.
First of all excuse me if when you read all the question you think isn't clear or question should be edited, please, make a edit and i will accept it.
Routes
Route::get('project/{id}', ['uses' => 'AdminController#showProject', 'as' => 'admin.projects.show']);
What I want to do
Render a view with information of two tables.
Tables information
First table is called projects and I have this fields: id, slug, order, public, pathheader and pathhome.
Second table is called project_translation where I have this fields: id, locale, project_id, title, description.
Query problem
I need a query where I get the info of the project I pass on url. This will look like this (is working):
$project = Project::find($id);
And I print the data with {{$project->fieldname}}
Now, I want to retrieve the data of the translation with the same project id. I was doing it with:
$translation = ProjectTranslation::find($id);
But of course, return me the data of the ProjectTranslation with the ID i passed on URL.
Question
How should look the query where I get the data of the project_translations with the same project_id ?
Thanks a lot, if need more information or just isn't clear. Please put a comment.
Try doing this:
$project = Project::find($id);
$translation = ProjectTranslation::where('project_id', $id)->first();
Do that in the controller and then you can pass this data to the view:
return view('sample', ['project' => $project, 'translation' => $translation]);
Just use the $id to find all records on ProjectTranslation with project_id equals to $id like this:
$translation = ProjectTranslation::where('project_id',$id)->get();
If you just have one record on ProjectTranslation, then you can get like:
$translation = ProjectTranslation::where('project_id',$id)->first();
Hope you understand.
So recently I have been thinking and can't find a solution yet to this problem since my lack of development with doctrine2 and symfony query builder.
I have 2 tables:
Goals: id,user_id,target_value...
Savings: id,goal_id,amount
And I need to make a select from goals (all the informations in my table are from the goals table, except that I need to make a SUM(amount) from the savings table on each goal, so I can show the user how much did he saved for his goal)
This is the MySQL query:
select
admin_goals.created,
admin_goals.description,
admin_goals.goal_date,
admin_goals.value,
admin_goals.budget_categ,
sum(admin_savings.value)
from admin_goals
inner join admin_savings on admin_savings.goal_id=admin_goals.id
where admin_goals.user_id=1
group by admin_goals.id
It returns what I want but I have no idea how to implement it with doctrine or query builder, can you please show me an example in both ways?
I highly appreciate it !
I am going to assume you need this fields only and not your AdminGoals entity. On your AdminGoalsRepository you can do something like this:
public function getGoalsByUser(User $user)
{
$qb = $this->createQueryBuilder('goal');
$qb->select('SUM(savings.value) AS savings_value')
->addSelect('goal.created')
->addSelect('goal.description')
->addSelect('goal.goalDate')
->addSelect('goal.value')
->addSelect('goal.budgetCat') //is this an entity? it will be just an ID
->join('goal.adminSavings', 'savings', Join::WITH))
->where($qb->expr()->eq('goal.user', ':user'))
->groupBy('goal.id')
->setParameter('user', $user);
return $qb->getQuery()->getScalarResult();
}
Keep in mind that the return object will be an array of rows, each row is an associated array with keys like the mappings above.
Edit
After updating the question, I am going to change my suggested function but going to leave the above example if other people would like to see the difference.
First things first, since this is a unidirectional ManyToOne between AdminSavings and AdminGoals, the custom query should be in AdminSavingsRepository (not like above). Also, since you want an aggregated field this will "break" some of your data fetching. Try to stay as much OOP when you are not just rendering templates.
public function getSavingsByUser(User $user)
{
$qb = $this->createQueryBuilder('savings');
//now we can use the expr() function
$qb->select('SUM(savings.value) AS savings_value')
->addSelect('goal.created')
->addSelect('goal.description')
->addSelect('goal.goalDate')
->addSelect('goal.value')
->addSelect('goal.budgetCat') //this will be just an ID
->join('savings.goal', 'goal', Join::WITH))
->where($qb->expr()->eq('goal.user', ':user'))
->groupBy('goal.id')
->setParameter('user', $user);
return $qb->getQuery()->getScalarResult();
}
Bonus
public function FooAction($args)
{
$em = $this->getDoctrine()->getManager();
$user = $this->getUser();
//check if user is User etc depends on your config
...
$savings = $em->getRepository('AcmeBundle:AdminSavings')->getSavingsByUser($user);
foreach($savings as $row) {
$savings = $row['savings_value'];
$goalId = $row['id'];
$goalCreated = $row['created'];
[...]
}
[...]
}
If you use createQuery(), then you can do something like this:
$dqlStr = <<<"DSQL"
select
admin_goals.created,
admin_goals.description,
admin_goals.goal_date,
admin_goals.value,
admin_goals.budget_categ,
sum(admin_savings.value)
from admin_goals
inner join admin_savings on admin_savings.goal_id=admin_goals.id
where admin_goals.user_id=1
group by admin_goals.id
DSQL;
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery($dqlStr);
$query->getResult();
On the other hand, if you would like to use createQueryBuilder(), you can check this link: http://inchoo.net/dev-talk/symfony2-dbal-querybuilder/
I want to get all rows , certain columns using CActive record
I heard about findAll(); but it returns all rows, colums
$models = Users::model()->findAll();
How to get certain columns for example, only username, password for all users?
You can do with CDbCriteria
$criteria = new CDbCriteria;
$criteria->select = 't.username, t.password '; // select fields which you want in output
$models = Users::model()->findAll($criteria);
If you want the result in the form of array try this
$records= Yii::app()->db->createCommand()
->select('username,password')
->from('users')
->queryAll();
If as an object then kumar_v has already given an answer
the Kumar_v 's answer is completely correct, but if you want only username and password (or any two fields),
you can also use CHtml::listData() function like this :
$users=CHtml::listData(Users::model()->findAll(array('condition'=>'*condition*',
'limit'='*limit*')),"username", "password");
the $users is an array like this :
$users = array(
'username1'=>'password1',
'username2'=>'password2',
.
.
.
);
and of course you can access to a username's password simply by $users['username1']
You could use as usual sql query but getting so would not be in yii standard
So get findAll() and get the data that you want. that is proposed and best.