I want to get only the list of values in the first column of the query.
$types = $em->getRepository('MyBundle:Notice')
->createQueryBuilder('n')
->select('n.type')
->groupBy('n.type')
->getQuery()
->getResult();
exho json_encode($types);
Result
[{"type":"foo"},{"type":"bar"},{"type":"baz"}]
I want to get a result
["foo","bar","baz"]
Of course, I can manually sort out the data and get the result I needed.
foreach ($types as $key => $type) {
$types[$key] = $type['type'];
}
But I want to use the standard method, if any. Unfortunately, I did not find such a method in the documentation. Maybe I'm bad looking)
Related
I'm trying to figure out how to correctly iterate on an array in a symfony 5 repository custom query.
I explain myself. App user may check several values on a page. I want to display objects that matches all (but not necessarily only) the checked values.
I easily catch an array of the values that I send to a controller with ajax but I encounter issues with my custom query.
Values matches the "label" parameter of a table (Tag) which is related (ManyToMany) to the table (Flash) I select with my query.
So far, I tried a lot of things, like :
public function getFlashesByTagsList($tags)
{
$qb = $this->createQueryBuilder('f');
$andX = $qb->expr()->andX();
$qb->join('f.tags', 't');
$qb->addSelect('t');
foreach($tags as $tag) {
$andX->add(
$qb->expr()->like('t.label', ':tag'),
$qb->setParameter(':tag', '%'.$tag.'%')
);
}
$qb->add('where', $andX);
$qb->orderBy('f.id', 'DESC');
$result = $qb->getQuery()->getResult();
return $result;
}
But nothing I tried worked. If only one value is sent, I get all the objects that has this value in their tags but as soon as there are more, it only get me the ones that matches the last one in the $tags array.
How can I get the total number of records for each of the grouped column(some_id) results generated in this eloquent query? (Answers generated using DB query builder or vanilla PHP also welcome).
$results = \App\MyModel::groupBy('some_id')
->whereNotNull('some_id')
// some query here to get sum of each grouped column records
->get();
The desired result would be such that when I'm looping through the results, I can also have a field called for example totalRecords for each grouped results. i.e.
foreach($results as $result) {
echo $result->totalRecords;
}
$results = DB::table('your_table')
->select('some_column_name', DB::raw('count(some_id) as totalRecords'))
->whereRaw('some_id IS NOT NULL')
->groupBy('some_id')
->get();
You can do like this :-
$results = \App\MyModel::select('*', DB::raw('count(some_id) as totalRecords'))
->groupBy('some_id')
->whereNotNull('some_id')
->get();
foreach ($results as $result) {
echo $result->totalRecords;
}
Collection Provide itself count() method.
But sometime once you fetch whole collection using get(). You can use count method on collection something like this:
$results = \App\MyModel::groupBy('some_id')
->whereNotNull('some_id')
// some query here to get sum of each grouped column records
->get();
dd($results->count());
Also, If your data is not collection then Php array's provide you count method you can use that too:
dd(count($results));
I used dd method just for debuging purpose.That will show you result before actual output.
count() method of array will help you to count collection as well as sub collection or array of sub array.
Good luck !!!
When building a query to find multiple values from a model, eloquent would look something like this:
return Contact::whereIn('user_name', explode(',', $userNames)
But let's say that the value for userNames is ['foo', 'bar']; but I only have foo as a valid username, is there a way to get bar (all failed to find) out as part of the same query without having to compare the result ->get() against the request?
It's not possible to get the query to return the list of username that doesn't exist from the given condition. But you could do this.
$allUserNames = explode(',', $userNames);
$validUserNames = Contact::whereIn('user_name', $allUserNames)
->pluck('user_name')
->toArray();
$invalidUserNames = array_values(array_diff($allUserNames, $validUserNames));
You can use array diff to remove the unvalid value form the select region, and you lost the ->get() to get the results;
return Contact::whereIn('user_name', array_diff(explode(',', $userNames, ['bar']))->get()
I'm using a personal request in symfony witch is:
public function findByReferenceUser($Reference, $User)
{
$qb = $this->createQueryBuilder('a')
->select('a')
->join('a.Reference', 'r')
->where('r.id = :refId')
->setParameter("refId", $Reference->getId())
->join('a.User', 'u')
->andWhere('u.id = :userId')
->setParameter("userId", $User->getId());
return $qb->getQuery()->getOneOrNullResult();
}
But it doesn't work properly.
I'm getting 3 results witch are of type NULL,NULL, Boolean. I'm using this to check it:
$list_article = $RArticle->findByReferenceUser($reference, $panier->getUser());
foreach ($list_article as $key => $article)
echo gettype($article);
My database works, and have the right informations.
Finnaly, this works:
$list_article = $RArticle->findAll();
foreach ($list_article as $key => $article)
echo gettype($article);
And print object, object.
So there is my questions: Why do I get NULL, NULL, Boolean in the first case and how do I fixe it?
Thank you for your help! :)
When using getOneOrNullResult, Doctrine will Retrieve a single object. If no object is found null will be returned. here.
If you want several object, you should use getResult
findAll() returns array of objects, such as array('key' => 'object'), that's why you are getting correct records, getOneOrNullResult() returns single object (not array, foreach won't work), if you want to retrieve multiple records you need to use getResult()
I have a list of news stories in my laravel website. On the /news/ page a quick list of stories is shown.
Now I want to allow users to filter news. For example, only show "sports" stories.
In my controller I did this:
$input = Input::all();
$events = DB::table('news')
->where('category', '=', $input['type'])
->order_by('created_at', 'desc')
->paginate(10);
Now, this allows me to visit /news?type=sports and it correctly only shows news items within the sports category. This only works if a type is given though, and will obviously fail if there is no type given.
What is the best solution to this? I know I can check to see if $input['type'] exists, and if it does, write a completely new, second "$news = DB::table('news')..." code, but I am thinking that I may actually want to have multiple user inputs, which would make that option not work. For example, what if I want to sort by type and location? Something like /news?type=sports&area=chicago -- what would I do then?
I know I must be missing something obvious here. Can anyone point me in the right direction?
I think you can do it using a foreach loop, for example
$input = Input::all();
So, you'll get something like this (you should check $input is not null)
Array
(
[type] => sports
[area] => chicago
)
Now, select the table like
$events = DB::table('news');
Now loop the $input like (for multiple dynamic where clause)
foreach ($input as $key => $value) {
$events->where($key, $value);
}
$result = $users->get();
Or you can use orderBy like (for multiple dynamic orderBy clause)
$events = DB::table('news')->where('category', $input['type']);
foreach ($input as $key => $value) {
$events->orderBy($key); // also, you can use ASC/DESC as second argument
}
$result = $users->get();
or you can use
$result = $users->paginate(10);