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()
Related
I have the following code in an entity repository:
$rows = $this->createQueryBuilder('t')
->select(['t.idColumn', 't.valueColumn'])
->where('t.foo = :foo')
->orderBy('t.idColumn', 'ASC')
->setParameter('foo', $foo)
->getQuery()
->getArrayResult(); // This returns [[idColumn => ..., valueColumn => ...], ...]
$data = [];
foreach ($rows as $row) {
$data[$row['idColumn']] = abs($row['valueColumn']); // Remapping to [id => value]
}
return $data;
Is there any way to get rid of the custom remapping natively? I know that you can use the indexBy parameter, but that only gets me the correct keys but not values.
P.S. I know of array_column(), but that's an extra step that I have to make every time, not to mention it doesn't work on methods that entities have.
P.P.S. This is not using Symfony.
It does not appear this is a feature implemented in the QueryBuilder, however fetchAllKeyValue was added in DBAL 2.11 to the Connection object.
Commit, usage
I am trying to loop through an array of ids to get data from another table, I mean I want to get latest queues of every schedule id we are looping in it.
So first i have $schedules:
$schedules = [{"id":19},{"id":18},{"id":15}]
And the foreach loop is like this:
$queues= [];
foreach ($schedules as $schedule) {
$queues[] = Queue::withTrashed()
->latest()
->where('schedule_id', $schedule);
}
return $queues;
when i return queues it's showing :
Object of class Illuminate\Database\Eloquent\Builder could not be converted to string
The error that shows is related to you are not running the query, you need a ->get() at the end of Queue::...->where(...)->get() to do it.
if you dont do it, as Dhananjay Kyada say in his answer:
it will try to return a query object
But to return a response:
The Response content must be a string or object implementing __toString()
Next, we need to tackle one more thing.
If you are defining the variable $schedules and assigning it the value as it is shown in the question:
$schedules = [{"id":19},{"id":18},{"id":15}]
try to do it taking the JSON as string and converting it into a PHP variable with json_decode:
$schedules = json_decode('[{"id":19},{"id":18},{"id":15}]');
Then you can use the id values in you where clause:
->where('schedule_id', $schedule->id)->get()
Maybe because you are not getting the result from your query. Because it is just a query it will return a query object. You need to add ->get() in order to get the result. You can try the following code:
$queues = [];
foreach ($schedules as $schedule) {
$queues[] = Queue::withTrashed()
->latest()
->where('schedule_id', $schedule)->get()->toArray();
}
return $queues;
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)
I'm using Laravel 4. Say I have an Eloquent model (Patient) and I want to get a patient with the name Bob, I would do this:
$patient = Patient::where('name', '=', 'Bob');
What is the best way to check to see if $patient is a valid record?
If the database query does not find any matching results, it returns null. Therefore...
$patient = Patient::where('name','=','Bob')->first();
if ( is_null($patient) ) {
App::abort(404);
}
(Note: in your original question you forgot ->first() (or ->get()) in your query. Don't forget that or else you will get an Eloquent object instead of a result.)
use this:
$patient = Patient::where('name', '=', 'Bob')->firstOrFail();
it will return Eulqouent model on success or throw ModelNotFoundException upon failure.
I know this is old, but this came up as the 2nd google hit on a search, so . . . for cases where you are not expecting one record or cannot use ->firstOrFail() (my use case is an async typeahead api that returns up to 10 results) the only thing that worked for me was count():
$patient = Patient::where('name', '=', 'Bob')->get(); //you could have more than one bob
if (!count($patient)) {
return 'No records found';
}
$patient = Patient::where('name','Bob')->get();
if ( $patient->isEmpty() ) {
return response(['error' => 'Record not found'], 404);
}
Something like Patient::where('name', '=', 'Bob')->exists() may work. It will return a boolean.
Just use empty() from native php will solve everything, if object null it will return true, if laravel's collection from query builder is empty (but initialized) it will return true too.
$contributor = Contributor::whereVendor('web')->first();
if(empty($contributor)){
...
}
use findOrFail($id) in case of you are passing id parameter to fetch a single record
I ended up on this while seeking solution of ::find($id)->firstOrFail syntax which is error-full.
$patient = Patient::findOrFail($id);
I've a method that returns a Doctrine_Collection, with a whereIn() clause :
public function getByValues($values)
{
if (!is_array($values))
throw new sfException('Wrong parameter type. Excepted array.');
return Doctrine_Query::create()
->from('Anomaly a')
->whereIn('a.value', $values);
}
However, when $values is an empty array, this method return all the rows that are in the AnomalyTable. This isn't an unexpected behavior, as documented in Doctrine documentation, and written here : Doctrine where in with Doctrine_Query
However, I would like to return an empty Doctrine_Collection instead of the result of my query, when $values is an empty array.
Any ideas on how I can do that ?
Thanks =)
Edit:
Adding an impossible clause, like ->where('1=0') would do the trick, but it is an unnecessary request to the DB server. Does anyone have a better idea ?
And what about (you need also the execute method to get the result of the query ! with that the return type will be the same everytime) :
public function getByValues($values)
{
if (!is_array($values))
throw new sfException('Wrong parameter type. Excepted array.');
if (empty($values)) {
return new Doctrine_Collection('Anomaly');
}
return Doctrine_Query::create()
->from('Anomaly a')
->whereIn('a.value', $values)
->execute()
;
}
By value, I assume you mean $values right? just add something to check if values is empty and then manually supply an empty collection.
if(empty($values))
return Doctine_Query::create()->from('Anomaly a')->where('1=0');
if(count($values)){
return Doctrine_Query::create()
->from('Anomaly a')
->whereIn('a.value', $values);
} else {
return Doctine_Query::create()
->from('Anomaly a')
->where('0=1');
}
I think it's impossible to do that.
The Doctrine_Collection is more than a resultset/array of objects. It also has means of deleting and adding objects and keeping that state.
That's probably also why many native Doctrine functions return FALSE when no results were found. (For instance, the NestedSet functions).
So, for you it's probably best to return FALSE as well. or maybe an empty array. Both arrays as Doctrine_Collection can be used in a foreach loop and count function.
Should you want to use the delete and add functions, you could just call the constructor.
I personnaly use the following trick:
public function getByValues($values)
{
if (!is_array($values))
throw new sfException('Wrong parameter type. Excepted array.');
$values = empty($values) ? array(-1) : $values;
return Doctrine_Query::create()
->from('Anomaly a')
->whereIn('a.value', $values);
}
Works great even if somewhat hackish.