I'm trying to return two columns ('question' and 'reponse') from two different table (also named 'question' and 'reponse') using a createQueryBuilder. I have no problem when I return one column, but it doesn't work when I try adding a new Select option.
My Controller that render my view and the data correctly :
public function play(Request $request) {
$id = $request->query->get('id');
$cat = $this->repository->findIdQuestion($id);
return $this->render('quiz_select.html.twig', [
'question' => $cat
]);
Here is my Question Repository that works when I remove the 'addSelect'
What can I do ?
public function findIdQuestion($id) {
return $this->createQueryBuilder('question')
->addSelect('reponse')
->from('App\Entity\Reponse', 'reponse')
->where('question.id_categorie = :id')
->setParameter('id', $id)
->getQuery()
->getResult();
}
I get that Error :
`An exception occurred while executing 'SELECT q0_.id AS id_0, q0_.id_categorie AS id_categorie_1, q0_.question AS question_2, r1_.id AS id_3, r1_.id_question AS id_question_4, r1_.reponse AS reponse_5, r1_.reponse_expected AS reponse_expected_6, r1_.question_id AS question_id_7 FROM question q0_, reponse r1_ WHERE q0_.id_categorie = ?' with params ["2"]:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'r1_.question_id' in 'field list'`
I'm not sure to understand what do you want to do. But I suppose you want to get a question and the reponse related to this question.
For doing that, you need to make a join between those tables.
You can use for example leftJoin
$query->leftjoin('App\Entity\Reponse','reponse','WITH','reponse.id = question.reponse_id')
Note that i supposed that there is reponse_id in you question table.
Be free to replace it by what you want.
For more precisions, you can check doctrine documentation.
https://www.doctrine-project.org/index.html
There a lot of examples, tutorials and a fully documentation
[Edited]
Problem there was that the field question_id was not in the table question in the database
Related
I wanna question about how to use order by inside eager load laravel eloquent, I already have a query like this :
$getData = StockIn::select(
StockIn::raw('group_concat(stock_ins.id_stock_in) as id_stock_ins'),
'stock_in_id_type'
)
->with(['type_of_items' => function ($query) {
$query->orderBy('type_of_item');
}])
->orderBy('type_of_items.type_of_item')
->groupBy('stock_ins.stock_in_id_type')
->get();
But when I compile the query and look to the result, the result of my query didn't make result with order by query, Am I making a mistake in my query so that the result is matching with my expectation? Thanks before
Here for my model :
Stock In :
public function type_of_items() {
return $this->belongsTo('App\TypeOfitem', 'stock_in_id_type');
}
Type Of Item :
public function stock_ins() {
return $this->hasMany('App\StockIn');
}
when I try to look on the console, the result of my query like this :
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'type_of_items.type_of_item' in 'order clause' (SQL: select group_concat(stock_ins.id_stock_in) as id_stock_ins, `stock_in_id_type` from `stock_ins` group by `stock_ins`.`stock_in_id_type` order by `type_of_items`.`type_of_item` asc)
You're currently using order by on eager loaded data.
Instead, you need to call it on the model itself.
$getData = StockIn::select(
StockIn::raw('group_concat(stock_ins.id_stock_in) as id_stock_ins'),
'stock_in_id_type'
)
->with(['type_of_items' => function ($query) {
$query->orderBy('type_of_item');
}])
->orderBy('type_of_items.type_of_item')
->groupBy('stock_ins.stock_in_id_type')
->get();
You can also try it out without groupBy first, to be sure you're getting the correct results
I'm trying to do that , get list of topics order by who has new post so I create a relation in topic model like that
public function latest_post()
{
return $this->hasOne(Post::class)->latest();
}
then I used the query like that
Topic::where('locale',$this->locale)->with('latest_post')->paginate(15)->sortByDesc('latest_post.created_at');
but it's giving me an error
Collection::render does not exist
so I change the sort to orderBy like that
Topic::where('locale',$this->locale)->with('latest_post')->orderBy('latest_post','DESC')->paginate(15);
but this also gives me another error
Unknown column 'latest_post' in 'order clause'
how can solve this issue?
Hmmm. Try this
$topic = Post::orderBy('created_at','desc')->first()->join('topics', 'topics.id', '=', 'posts.topic_id')->first();
Or in your post model:
public function Topic()
{
return $this->belongsTo(Topic::class, 'topic_id');
}
To get the last active topic:
$topic = Post::orderBy('created_at','desc')->first()->Topic;
doctrine/symfony project:
i try to only get results if a reference is set.
so the colum for the relation can be filled with reference ids or it can be null if no reference is "set"... im not able to exclude the actual datasets with a null column
$qb = $this->em->createQueryBuilder();
$qb->select('am', 'lb')->from('MyBundle:Brand', 'am')
->leftJoin('MyBundle:XBuyer', 'lb')
->where('lb.id = am.buyer')
->andWhere('am.buyer IS NOT NULL');
another format i tried
$qb->select('am', 'lb')->from('MyBundle:Brand', 'am')
->leftJoin('MyBundle:XBuyer', 'lb')
->where('lb.id = am.buyer')
->andWhere('am.buyer != :buyer_id_val')
->setParameter('buyer_id_val', '');
also
$qb->select('am', 'lb')->from('MyBundle:Brand', 'am')
->leftJoin('MyBundle:XBuyer', 'lb')
->where('lb.id = am.buyer')
->andWhere($qb->expr()->isNotNull('am.buyer'));
am.buyer is the reference to another table - its actually buyer_id in the brands table
followed by
$data = $qb->getQuery()->execute(null, Query::HYDRATE_SCALAR);
no idea what im doing wrong here
the problem was that i'm still thinking in the context of the database (other projects) but in the case of using doctrine it was necessary to think in the context of an object - more specific if there is an relation between entities.
the actual IS NOT NULL expression wasnt the problem - the problem was the actual leftJoin on an entitiy instead of the relation-"name".
$qb->select('am', 'lb')->from('MyBundle:Brand', 'am')
->leftJoin('am.buyer', 'lb')
->where('am.buyer IS NOT NULL')
->andWhere('lb.id = am.buyer');
thanks guys for all the comments and support in this little timeframe
in my case,
$qb = $this->em->createQueryBuilder();
generated :
Too few arguments to function Doctrine\ORM\EntityRepository::createQueryBuilder()…
I finally wrote:
$qb = $this->em->createQueryBuilder('am');
$qb->select('am')
->leftJoin('am.buyer', 'lb')
->where('lb.id = am.buyer')
->andWhere('am.buyer IS NOT NULL');
->orderBy('am.id', 'ASC')
->setMaxResults(30)
->getQuery()
->getResult()
;
which works fine!
Nota: with Symfony 4.2.3
I have a problem in retrieve data from two difference MySQL databases
$em = $this->doctrine->emDetails;
$qb = $em->createQueryBuilder();
$qb->select('g.gradeId as grade_id', 'g.gradeName as grade_name', 'g.rank', 'ay.academicId as academic_year_id');
$qb->from('Entity\Grades', 'g');
$qb->leftjoin('g.academicYear', 'ay');
$qb->where('ay.academicId = :academicId');
$qb->setParameter('academicId', $data);
$result = $qb->getQuery()->getResult();
return $result;
academicYear exist in X database
and Grades exist in Y database
i have get the following Error
Base table or view not found: 1146 Table 'Y.Academic_years' doesn't exist
How i can solve the problem
To query two different database you need to work with two entity managers.
If you're working with symfony you can find how to do it here :
http://symfony.com/doc/current/doctrine/multiple_entity_managers.html
Official doc explains it very clearly.
This is my custom finder method inside DynamicViewsTable.php
public function findAccessibleByUser(Query $query, array $options)
{
if (empty($options['User']['id'])) {
throw new Exception("Current User not set", 1);
}
$query->select(['DynamicViews.id', 'DynamicViews.title', 'UsersAccessDynamicViews.ordinal_ranking'])
->contain(['UsersAccessDynamicViews'])
->where([
'UsersAccessDynamicViews.user_id' => $options['User']['id'],
])
->order(['UsersAccessDynamicViews.ordinal_ranking' => 'ASC']);
return $query;
}
The error I keep getting is:
Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'UsersAccessDynamicViews.ordinal_ranking' in 'field list'
and the query shown in the error page is:
SELECT DynamicViews.id AS `DynamicViews__id`, DynamicViews.title AS `DynamicViews__title`, UsersAccessDynamicViews.ordinal_ranking AS `UsersAccessDynamicViews__ordinal_ranking` FROM dynamic_views DynamicViews WHERE UsersAccessDynamicViews.user_id = :c0 ORDER BY UsersAccessDynamicViews.ordinal_ranking ASC
DynamicViews hasMany UsersAccessDynamicViews
While you can include any type of associaition using contain(), matching something does only work for 1:1 and n:1 associations, that is hasOne and belongsTo, as these are the only associations where contain() will join in the related tables.
For all other purposes you will have to use either matching() (requires a recent dev snapshot in order to work when combined with contain(), escpecially for more complex combinations)
$query
->select(['DynamicViews.id', 'DynamicViews.title', 'UsersAccessDynamicViews.ordinal_ranking'])
->contain(['UsersAccessDynamicViews'])
->matching('UsersAccessDynamicViews', function ($q) use ($options) {
return $q->where([
'UsersAccessDynamicViews.user_id' => $options['User']['id']
]);
})
->order(['UsersAccessDynamicViews.ordinal_ranking' => 'ASC']);
join in the related tables manually:
$query
->select(['DynamicViews.id', 'DynamicViews.title', 'UsersAccessDynamicViews.ordinal_ranking'])
->contain(['UsersAccessDynamicViews'])
->innerJoin('UsersAccessDynamicViews', [
'UsersAccessDynamicViews.dynamic_view_id = DynamicViews.id',
'UsersAccessDynamicViews.user_id' => $options['User']['id']
])
->order(['UsersAccessDynamicViews.ordinal_ranking' => 'ASC']);
or query from the other table.
See also
http://book.cakephp.org/3.0/en/orm/retrieving-data-and-resultsets.html#filtering-by-associated-data
http://book.cakephp.org/3.0/en/orm/query-builder.html#adding-joins