mongodb query return simple array - php

How can I make mongodb return results in a simple array?
Ex:
My first query:
$user_ids = $dm->createQueryBuilder('AcmeBundle:Users')
->hydrate(false)
->select('_id')
->getQuery()
->execute();
My second query:
$no_credit = $dm->getRepository('AcmeBundle:Places')
->createQueryBuilder('places')
->distinct('_id')
->field('visited.users')
->in($user_ids)
->getQuery()
->count();
How can I achieve this when the first query won't return an array of MongoID objects?

I must admit I do not symfony however I believe it returns an implmentation of MongoCursor as such getting the cursor object and doing iteratortoarray or something similar will solve the problem in a hackish way.

Related

laravel query retun object instead of string

I wrote this query to get string type(value), which is up or down, instead it returns me an object.
$o_response = $this->statuses()
->where('status_id', $o_health_status->id)
->orderBy('created_at', 'desc')
->select('values')
->first();
this is the result :
{"values":"up","pivot":{"notification_id":1,"status_id":1,"values":"up","created_at":"2016-11-04 13:18:29","updated_at":"2016-11-04 13:18:29"}}
It returns an object instead of string. Why?
Laravel eloquent returns collection ex.->get() or object ex. ->first() .
So i think you will need just to get column something like
$o_response = $o_response->values;

How to solve Object of class stdClass could not be converted to string while returning data into view in laravel?

This is my Laravel controller code
public function switchInfo($prisw, $secsw){
$cur_sw_pair_id = DB::table('sw_pairs')
->select('sw_pair_id')
->where('pri_sw','=',$prisw)
->where('sec_sw','=',$secsw)
->get();
$infolist = DB::table('cust_sw_pair')
->select('interface','pri_sw_vlan','sec_sw_vlan','pri_sw_admin_status','sec_sw_admin_status','description')
->where('sw_pair_id', '=', $cur_sw_pair_id)
->get();
return view('switchinfo.switchinfoview',compact('infolist'));
}
when this code executing it gives Object of class stdClass could not be converted to string error. How can i solve this? How can i pass my infolist into switchinfoview view without getting this error?
You can use pluck() to get value of a column.
Your first query should like this:
$cur_sw_pair_id = DB::table('sw_pairs')
->where('pri_sw','=',$prisw)
->where('sec_sw','=',$secsw)
->pluck('sw_pairs');
Keep the second query as it is.
Hope it will help.
The issue is that ->get() returns a collection, which is a 0-indexed collection of results (rows) from the database. In your case, you want to be using the following query:
$cur_sw_pair_id = DB::table('sw_pairs')
->select('sw_pair_id')
->where('pri_sw','=',$prisw)
->where('sec_sw','=',$secsw)
->first();
And then accessing the property sw_pair_id of $cur_sw_pair_id, like so:
$infolist = DB::table('cust_sw_pair')
->select('interface','pri_sw_vlan','sec_sw_vlan','pri_sw_admin_status','sec_sw_admin_status','description')
->where('sw_pair_id', '=', $cur_sw_pair_id->sw_pair_id)
->first();
Then, in your view, you can access all the properties (anything in the ->select() statement) of $infolist using $infolist->PROPERTY_HERE
Note that using ->first() is essentially using the same as ->get();, but you have to access the results of ->get() using an index, so
$cur_sw_pair_id[0]->sw_pair_id
Hope that provides some insight for you.

What is the best way to check if an Eloquent query returns no answer?

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);

How to fetch class instead of array in Doctrine 2

I am able to fetch my data from database by using this structure:
$user = $this->getDoctrine()
->getRepository('AcmeDemoBundle:Emails')
->find(8081);
When I do that, I am able to get my data like this:
$user->getColumnNameHere();
Basically I am able to use Entity Class.
But if I want to use QueryBuilder instead of find I am only getting associative arrays.
$product->createQueryBuilder('p')
->setMaxResults(1)
->where('p.idx = :idx')
->select('p.columnNameHere')
->setParameter('idx', 8081)
->orderBy('p.idx', 'DESC')
->getQuery();
$product = $query->getResult();
$product returnds as array. Is it possible to fetch it withj Entity Managaer Class? If yes, how?
I digg the documentation but it seems not possible or not exist in the doc or I'm just blind :)
Yes you can, usually using:
$repository
->createQueryBuilder('p')
->getQuery()
->execute()
;
This should return you an array of entities.
If you want to get a single entity result, use either getSingleResult or getOneOrNullResult:
$repository
->createQueryBuilder('p')
->getQuery()
->getOneOrNullResult()
;
Warning: These method can potentially throw NonUniqueResultException.
Edit: Ok, so the question was about partial objects: http://docs.doctrine-project.org/en/latest/reference/partial-objects.html
you can get an object instead of array by using "Partial Objects".
here is a tested example with DoctrineORM 2.2.2:
// create query builder
// $em is the EntityManager
$qb = $em->createQueryBuilder();
// specify the fields to fetch (unselected fields will have a null value)
$qb->select ('partial p.{id,pubDate,title,summary}')
->from ('Project\Entity\Post', 'p')
->where ('p.isActive = 1')
->orderBy ('p.pubDate', 'desc');
$q = $qb->getQuery();
$result = $q->getResult();
var_dump($result); // => object
If you wish to return an object from your original query:
$product->createQueryBuilder('p')
->setMaxResults(1)
->where('p.idx = :idx')
->select('p.columnNameHere')
->setParameter('idx', 8081)
->orderBy('p.idx', 'DESC')
->getQuery();
$product = $query->getResult();
Remove this line
->select('p.columnNameHere')
As soon as you use select, it will return an array...
getResult() method returns a collection (an array) of entities. Use getSingleResult() if you're going to fetch only one object.
EDIT:
Oh, I just noticed that you want to fetch a single field of a single object. Use getSingleScalarResult() as #Florian suggests.

Doctrine ORM, two different querys produce the same result set

I'm using Doctrine 1.2 and Symfony 1.4.
In my action, I have two different query that return different result set. Somehow the second query seem to change the result (or the reference?) of the first one and I don't have any clue why..
Here is an example:
$this->categories = Doctrine_Query::create()
->from('Categorie AS c')
->innerJoin('c.Activite AS a')
->where('a.archive = ?', false)
->execute();
print_r($this->categories->toArray()); // Return $this->categories results, normal behavior.
$this->evil_query = Doctrine_Query::create()
->from('Categorie AS c')
->innerJoin('c.Activite AS a')
->where('a.archive = ?', true)
->execute();
print_r($this->categories->toArray()); // Should be the same as before, but it return $this->evil_query results instead!
Why Doctrine behave this way ? It's totally driving me crazy. Thanks!
To make it simple it seem like the Query 2 are hijacking the Query 1 result.
Use something like this between queries ($em - entity manager):
$em->clear(); // Detaches all objects from Doctrine!
http://docs.doctrine-project.org/en/2.0.x/reference/batch-processing.html
In the API docs for the toArray() method in Doctrine_Collection it says:
Mimics the result of a $query->execute(array(), Doctrine_Core::HYDRATE_ARRAY);
I suspect to answer this question to your satisfaction you're going to have to go through the source code.
This seems like it has to be an issue of $this->categories and $this->evil_query pointing to the same place. What are the results of $this->evil_query === $this->categories and $this->evil_query == $this->categories?
Hubert, have you tried storing the query into a separate variable and then calling the execute() method on it?
I mean something like:
$good_query = Doctrine_Query::create()
->from('...')
->innerJoin('...')
->where('...', false)
;
$evil_query = Doctrine_Query::create()
->from('...')
->innerJoin('...')
->where('...', true)
;
$this->categories = $good_query->execute();
$this->evil_query = $evil_query->execute();
It seems like both attributes (categories and evil_query) are pointing at the same object.
Erm, after both queries you print_r the result of the first query - change the last line to print_r($this->evil_query->toArray()); to see the difference :)

Categories