Yii ActiveRecord Primary Key retrieval - activerecord

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

Related

Fetching only distinct data from table using hasura-graphql data provider in react-admin

I am working on a project where I have to fetch only distinct data from the table display in the dropdown. How can I do that? I am using '''hasura-graphql''' data-provider for it. So how can I get only distinct data from a particular column?
Thanks in advance.
I think passing a default "distinct_on" filter with the column name as value will do the job. Also, hasura recommends sorting by this column in first position.
It is typically recommended to use order_by along with distinct_on to
ensure we get predictable results (otherwise any arbitrary row with a
distinct value of the column may be returned). Note that the
distinct_on column needs to be the first column in the order_by
expression.
So i set default sort:
<ReferenceInput
reference="yourTable"
source="yourDistinctColumn"
sort={{field: "yourDistinctColumn", order: "ASC"}}//or DESC, your choice
filter={{distinct_on: "yourDistinctColumn"}}
>
<SelectInput optionText="yourDistinctColumn"/>
</ReferenceInput>
https://hasura.io/docs/1.0/graphql/manual/queries/distinct-queries.html

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

HappyBase - Is there an equivalent of find_one or scan_one?

All the rows in a particular HBase table that I am making a UI for happen to have the same columns and will have so for the foreseeable future. I would like my html data visualizer application to simply query for a single random row to take note of the column names, and put this list of column names into a variable to refer to throughout the program.
I didn't see any equivalent to find_one or scan_one in the docs for HappyBase.
What is the best way to accomplish this?
This will fetch only the first row:
row = next(table.scan(limit=1))
Additionally you can specify a filter string to avoid retrieving the values, which is only worthwile if your values are large and you're performing this query often.
I use the 'limit' option.
Here is my HappyBase Python code:
pool1 = happybase.ConnectionPool(size=2, host='172.00.00.01')
with pool1.connection() as conn1:
hTable = conn1.table('HBastTableHere')
for rowKey, rowData in hTable.scan( limit=1):
print rowData
You can create a Scanner object, without specifying the start row (so that it start at the first row in the table), and limit the scan to one row. You will get then the first row only.
From the HBase shell command it should look like this:
scan 'table_name', {LIMIT => 1}
I don't know for HappyBase but I think you should be able to do that

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

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.

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.

Resources