How to stop Doctrine from returning a primary key for every query - doctrine

I am kind of annoyed at Doctrine for returning primary keys in each and every query even though I don't want it to. Is there anyway to stop this ? coz I don't really want those damn primary keys along with my doctrine query results.
A query for instance that I have is:
$getAllDatesForUserQuery = $this->createQuery('s')
->select('s.datename')
->where('s.userid = ?',3)
->setHydrationMode(Doctrine::HYDRATE_ARRAY) ;
In this situation, it retrieves all the datenames as it should, but also happily returns the primary key column value. I DON"T WANT IT.
Is it me? or is it Doctrine ?

In a case like this where you want a simple array and only have a single field being selected, the answer is the Single Scalar Hydration mode. Use it like this:
$q = $this->createQuery('s')
->select('s.datename')
->where('s.userid = ?',3)
->setHydrationMode(Doctrine::HYDRATE_SINGLE_SCALAR);
You should find that the query will return a simple one-dimensional array containing only the value(s) you wanted.

Related

query to get only one item from target column in Laravel

Is there any query to get only one item from target column? below didn't working?
App\Job::whereNotNull('deleted_at')->pluck('customer_name')->first()
I wish to get just one item name from 'customer_name'
Now Laravel 5.6 using...
When using eloquent, using first will give you a single item, the first record matching your query. You can then access the property on that item:
// This will give you an instance of App\Job (or null)
$job = App\Job::whereNotNull('deleted_at')->first();
// You can then access the customer_name property on the object
$job->customer_name;
If you only want to retrieve that single column when you run your query, you can pass an array of columns to first.
App\Job::whereNotNull('deleted_at')->first(['customer_name']);
Assuming you're using the SoftDeletes trait in your model, your query will automatically have an additional check added to all of your queries to ensure that deleted_at is null. So when you're doing ->whereNotNull('deleted_at') you're adding an additional clause to ensure records are not null as well, so you won't have any records being returned.
If you want to look only at deleted records, you can use onlyTrashed():
App\Job::onlyTrashed()->first();
There is a built-in method for this: value('field')
App\Job::whereNotNull('deleted_at')->value('customer_name');
Docs: https://laravel.com/docs/5.6/queries, look for "Retrieving A Single Row / Column From A Table"
If you meant only one field but still as rows, you can use ->select('field') instead.
And since you want only trashed items, you can use ->onlyTrashed() instead of the not null check.
Soft deleting documentation: https://laravel.com/docs/5.6/eloquent#deleting-models
Try like this:
$job = \App\Job::selectRaw('customer_name')
->whereNotNull('deleted_at')
->first();
And use it like $job->customer_name

CouchDB View with Multiple Parameters

I have a database that has an id column and a ts column. I need to be able to pass in the id and a start time and end time to retrieve all the values during the specified period. Can I do this with a view, or do I need the view to return all of the values that match the id? My concern is that I will be returning and parsing a lot more data than I really care about. Here is the format of my DB from my current view, which simply returns everything that matches the id...
{"id":"62db2aa3472dce80b1f2193fc21d52fd","key":"A-Meter-KW","value":{"_id":"62db2aa3472dce80b1f2193fc21d52fd","_rev":"1-6aadd58f4f5dabacf6f4f638396246d0","id":"A-Meter-KW","ts":1437969600000,"tz":"New_York","val":"191kW"}},
{"id":"62db2aa3472dce80b1f2193fc21d5100","key":"A-Meter-KW","value":{"_id":"62db2aa3472dce80b1f2193fc21d5100","_rev":"1-71155153c0f03c49b02850bee5535e22","id":"A-Meter-KW","ts":1437968700000,"tz":"New_York","val":"190kW"}},
{"id":"62db2aa3472dce80b1f2193fc21d45d7","key":"A-Meter-KW","value":{"_id":"62db2aa3472dce80b1f2193fc21d45d7","_rev":"1-661511616958d45fdff3307600d2a9ed","id":"A-Meter-KW","ts":1437967800000,"tz":"New_York","val":"189kW"}},
{"id":"62db2aa3472dce80b1f2193fc21d3c23","key":"A-Meter-KW","value":{"_id":"62db2aa3472dce80b1f2193fc21d3c23","_rev":"1-4e97cfc6cb97ddc65f04efd9043b3abd","id":"A-Meter-KW","ts":1437966900000,"tz":"New_York","val":"188kW"}},
{"id":"62db2aa3472dce80b1f2193fc21d2e35","key":"A-Meter-KW","value":{"_id":"62db2aa3472dce80b1f2193fc21d2e35","_rev":"1-120298e95c9d2b4b9cdf438836b6c0c0","id":"A-Meter-KW","ts":1437966000000,"tz":"New_York","val":"187kW"}},
{"id":"62db2aa3472dce80b1f2193fc21d22b0","key":"A-Meter-KW","value":{"_id":"62db2aa3472dce80b1f2193fc21d22b0","_rev":"1-61e55d02bd8f0c601274b904f46c9f34","id":"A-Meter-KW","ts":1437965100000,"tz":"New_York","val":"186kW"}},
{"id":"62db2aa3472dce80b1f2193fc21d1ce2","key":"A-Meter-KW","value":{"_id":"62db2aa3472dce80b1f2193fc21d1ce2","_rev":"1-b4fe80563c70a40981e293af9c6a87b3","id":"A-Meter-KW","ts":1437964200000,"tz":"New_York","val":"185kW"}},
{"id":"62db2aa3472dce80b1f2193fc21d1ccc","key":"A-Meter-KW","value":{"_id":"62db2aa3472dce80b1f2193fc21d1ccc","_rev":"1-bdf1881c4270e68e7a7ed90a1d945228","id":"A-Meter-KW","ts":1437963300000,"tz":"New_York","val":"184kW"}},
{"id":"62db2aa3472dce80b1f2193fc21d1303","key":"A-Meter-KW","value":{"_id":"62db2aa3472dce80b1f2193fc21d1303","_rev":"1-404d5934fc882aa36e6d355d9a3485ae","id":"A-Meter-KW","ts":1437962400000,"tz":"New_York","val":"183kW"}},
{"id":"62db2aa3472dce80b1f2193fc21d0941","key":"A-Meter-KW","value":{"_id":"62db2aa3472dce80b1f2193fc21d0941","_rev":"1-64288d1c98e9b93aa6c546acb1e02078","id":"A-Meter-KW","ts":1437961500000,"tz":"New_York","val":"182kW"}}
...
... my current query is http://localhost:5984/hist/_design/hist/_view/byId?key=%22A-Meter-KW%22&descending=true. I'd like to passing a start and end time as well, something like http://localhost:5984/hist/_design/hist/_view/byId?key=%22A-Meter-KW%22&descending=true&start=1437963300000&end=1437966000000 but cannot figure out how to do this.
EDITED:
In order for Couch to match your query all the data (eg:A-Meter-KW and date) must be in the key, emitted by the view. So I think you might do something like:
emit([key,year,month,day],doc._id)
Then you can use the parameters startkey and endkey to filter the results properly.
Reference: http://guide.couchdb.org/draft/views.html#many
Side consideration: I would not use an "id" property inside my documents, because it could get easily confused with the "_id" (compulsory) one.

couchdb - retrieve unique documents for a view that emits non-unique two array keys

I have an map function in a view in CouchDB that emits non-unique two array keys, for documents of type message, e.g.
The first position in the array key is a user_id, the second position represents whether or not the user has read the message.
This works nicely in that I can set include_docs=true and retrieve the actual documents. However, I'm retrieving duplicate documents in that case, as you can see above in the view results. I need to be able to write a view that can be queried to return unique messages that have been read by a given user. Additionally, I need to be able to efficiently paginate the resultset.
notice in the image above that [66, true] is emitted twice for doc id 26a9a271de3aac494d37b17334aaf7f3. As far as I can tell, with the keys in my map function, I cannot reduce in such a way that unique documents will be returned.
the next idea I had was to emit doc._id also in the map function and reduce with group_level=exact the result being:
now I am able to get unique document ids, but I cannot get the documents without doing a second query. And even in the case of a second query, it will require a lot of complexity to do pagination like this (at least I think so).
the last idea I came up with is to emit the entire document rather than the doc._id in the third position in the array key, then I can access the entire document and likely paginate. This seems really brutish.
So my question is:
Is #3 above a terrible idea? Is there something I'm missing? Is there a better approach?
Thanks in advance.
See #WickedGrey's comment to the question. The solution is to ensure that I never emit the same key twice for one document. I do this in the map function by keeping track of the keys as I emit them in an array, then skipping the emit if the key exists in the array.

How do I sort, group a query properly that returns a tuple of an orm object and a custom column?

I am looking for a way to have a query that returns a tuple first sorted by a column, then grouped by another (in that order). Simply .sort_by().group_by() didn't appear to work. Now I tried the following, which made the return value go wrong (I just got the orm object, not the initial tuple), but read for yourself in detail:
Base scenario:
There is a query which queries for test orm objects linked from the test3 table through foreign keys.
This query also returns a column named linked that either contains true or false. It is originally ungrouped.
my_query = session.query(test_orm_object)
... lots of stuff like joining various things ...
add_column(..condition that either puts 'true' or 'false' into the column..)
So the original return value is a tuple (the orm object, and additionally the true/false column).
Now this query should be grouped for the test orm objects (so the test.id column), but before that, sorted by the linked column so entries with true are preferred during the grouping.
Assuming the current unsorted, ungrouped query is stored in my_query, my approach to achieve this was this:
# Get a sorted subquery
tmpquery = my_query.order_by(desc('linked')).subquery()
# Read the column out of the sub query
my_query = session.query(tmpquery).add_columns(getattr(tmpquery.c,'linked').label('linked'))
my_query = my_query.group_by(getattr(tmpquery.c, 'id')) # Group objects
The resulting SQL query when running this is (it looks fine to me btw - the subquery 'anon_1' is inside itself properly sorted, then fetched and its id aswell as the 'linked' column is extracted (amongst a few other columns SQLAlchemy wants to have apparently), and the result is properly grouped):
SELECT anon_1.id AS anon_1_id, anon_1.name AS anon_1_name, anon_1.fk_test3 AS anon_1_fk_test3, anon_1.linked AS anon_1_linked, anon_1.linked AS linked
FROM (
SELECT test.id AS id, test.name AS name, test.fk_test3 AS fk_test3, CASE WHEN (anon_2.id = 87799534) THEN 'true' ELSE 'false' END AS linked
FROM test LEFT OUTER JOIN (SELECT test3.id AS id, test3.fk_testvalue AS fk_testvalue
FROM test3)
AS anon_2 ON anon_2.fk_testvalue = test.id ORDER BY linked DESC
)
AS anon_1 GROUP BY anon_1.id
I tested it in phpmyadmin, where it gave me, as expected, the id column (for the orm object id), then the additional columns SQL_Alchemy seems to want there, and the linked column. So far, so good.
Now my expected return values would be, as they were from the original unsorted, ungrouped query:
A tuple: 'test' orm object (anon_1.id column), 'true'/'false' value (linked column)
The actual return value of the new sorted/grouped query is however (the original query DOES indeed return a touple before the code above is applied):
'test' orm object only
Why is that so and how can I fix it?
Excuse me if that approach turns out to be somewhat flawed.
What I actually want is, have the original query simply sorted, then grouped without touching the return values. As you can see above, my attempt was to 'restore' the additional return value again, but that didn't work. What should I do instead, if this approach is fundamentally wrong?
Explanation for the subquery use:
The point of the whole subquery is to force SQLAlchemy to execute this query separately as a first step.
I want to order the results first, and then group the ordered results. That seems to be hard to do properly in one step (when trying manually with SQL I had issues combining order and group by in one step as I wanted).
Therefore I don't simply order, group, but I order first, then subquery it to enforce that the order step is actually completed first, and then I group it.
Judging from manual PHPMyAdmin tests with the generated SQL, this seems to work fine. The actual problem is that the original query (which is now wrapped as the subquery you were confused about) had an added column, and now by wrapping it up as a subquery, that column is gone from the overall result. And my attempt to readd it to the outer wrapping failed.
It would be much better if you provided examples. I don't know if these columns are in separate tables or what not. Just looking at your first paragraph, I would do something like this:
a = session.query(Table1, Table2.column).\
join(Table2, Table1.foreign_key == Table2.id).\
filter(...).group_by(Table2.id).order_by(Table1.property.desc()).all()
I don't know exactly what you're trying to do since I need to look at your actual model, but it should look something like this with maybe the tables/objs flipped around or more filters.

Yii ActiveRecord Primary Key retrieval

I have looked around and have not found anything similar to what I am asking.
Short of extending the CActiveRecord class is there a way to query just the primary key values (or any column's values) of a table and have an array of those values returned instead of a collection of activerecord objects?
ie
ModelName::model()->getColumnValues('column_name');
I keep having to get a list of record that match a certain condition and then run through the results to pull out the column values I need. I would like to cut out the last step and just get the values instead of the entire record.
Any ideas?
Using a CDbCommand you can execute a query and fetch the results from one column with the queryColumn method. queryColumn returns the results from the first column.
Example:
$command = Yii::app()->db->createCommand("SELECT column FROM table WHERE ...");
$result = $command->queryColumn();

Resources