Laravel 3 Eloquent How to select column as - select

I'm trying to figure out how to give a column an alias using Eloquent.
So, in other words, how do I execute the following mysql query using Eloquent?
SELECT occupation AS test FROM users WHERE occupation = 'PIMP';
Thx in adv!

Eloquent returns a regular Fluent query. So you can try something like this (assuming your model name is 'User'):
$user = User::where_occupation('pimp')->get(array('occupation as test'));

This is how I have been able to do this in Laravel 5 using select() and passing the col name and the alias to that method (here I'm also using groupby() to restrict it to "DISTINCT" return values then using toarray() to return any array instead of a Collection Object:
$results = asset::select('model_code__c AS option')->whereRAW("model_code__c <> '' AND status = 'A'")->groupby('model_code__c')->get()->toarray();

Related

Expressing Postgresql VALUES command in SQLAlchemy ORM?

How to express the query
VALUES ('alice'), ('bob') EXCEPT ALL SELECT name FROM users;
(i.e. "list all names in VALUES that are not in table 'users'") in SQLAlchemy ORM? In other words, what should the statement 'X' below be like?
def check_for_existence_of_all_users_in_list(list):
logger.debug(f"checking that each user in {list} is in the database")
query = X(list)
(There is sqlalchemy.values which could be used like this:
query = sa.values(sa.column('name', sa.String)).data(['alice', 'bob']) # .???
but it appears that it can only be used as argument to INSERT or UPDATE.)
I am using SQLAlchemy 1.4.4.
This should work for you:
user_names = ['alice', 'bob']
q = values(column('name', String), name="temp_names").data([(_,) for _ in user_names])
query = select(q).except_all(select(users.c.name)) # 'users' is Table instance

Add a single field to model using raw SQL

I'm developing an extension for TYPO3 CMS 8.7.8. I'm using query->statement() to select all fields from a single table, plus 1 field from another table. I get a QueryResult with the proper models and I would like to have that 1 extra field added to them. Is that possible?
You can do SQL queries with the ->statement(...) method and in that, use normal JOIN commands
From the documentation
$result = $query->statement('SELECT * FROM tx_sjroffers_domain_model_offer
WHERE title LIKE ? AND organization IN ?', array('%climbing%', array(33,47)));
So you can do JOINs on whatever table you want to (also code from the documentation)
LEFT JOIN tx_blogexample_person
ON tx_blogexample_post.author = tx_blogexample_person.uid
But you will end up with the raw data from the mysql query. If you want to transform it into a object, use the Property Mapper
You can use JOIN in your sql statments like below.
$query = $this->createQuery();
$sql = 'SELECT single.*,another.field_anme AS fields_name
FROM
tx_single_table_name single
JOIN
tx_another_table_name another
ON
single.fields = another.uid
WHERE
O.deleted = 0
AND O.hidden=0
AND O.uid=' . $orderId;
return $query->statement($sql)->execute();

AEM: How to find the nodes with property name "customProp" and empty property value, using query builder?

There are nodes which have properties but no values.
I am trying to avoid those nodes in query builder using,
path=/content/
type=cq:Page
2_property=jcr:content/customProp
2_property.operation=exists
3_property=jcr:content/customProp
3_property.operation=unequals
3_property.value=
But the empty value condition (3_property) is being ignored.
How this can be achieved?
I had the issue to search for all occurrence of a propertiy with no value.
I constructed the following SQL2 Query:
SELECT * FROM [{{jcr:primaryType}}] AS ref WHERE ISDESCENDANTNODE([{{Start Path}}]) AND ref.[{{Property Name}}] = ''
In your case I think something like should work
SELECT * FROM [{{jcr:primaryType}}] AS ref WHERE ISDESCENDANTNODE([{{Start Path}}]) AND NOT(ref.[{{Property Name}}] = '')

Search database using Entity Framework. LIKE operator

I want to search one of my tables using Entity Framework 5. I don't know how many words there are in the query, but I want to match all of them.
query = hello
SELECT * FROM [table] WHERE [column] LIKE '%hello%'
query = hello world
SELECT * FROM [table] WHERE [column] LIKE '%hello%' AND [column] LIKE '%world%'
I know the function PATINDEX , but it doesn't work good enough. Why? I'll show you:
SELECT * FROM person WHERE PATINDEX('%test%.com%', email)>0
will match "test#email.com", but if the search word are ordered the other way, it will not find this person:
SELECT * FROM person WHERE PATINDEX('%.com%test%', email)>0
What is the most efficient way to create this query using EF?
using linq to entities you can use .Contains to do the equivilant in SQL
table(x => x.column).Where(y => y.ColumnName).Contains("hello");
Sorry forgot the where clause that should work.
You can build the query in a foreach loop:
var words = new[] {"com", "test"};
var table = <your initial DbSet or ObjectSet>
foreach (var word in words)
{
string word1 = word; // prevent modified closure.
table = table.Where(x => x.column.Contains(word1));
}
var result = table.ToList(); // Enumerate the composed linq query.
The Contains function translates to LIKE with the search term enclosed in % characters.

Best way to do an Inner Join using the Zend Framework?

It seems like there's a few different ways to join two tables using the Zend Framework, but I've never done it before so I don't know which is the best way to do it.
This is what I'm trying to do...
I have 3 tables in my database:
users
( id , name )
groups
( id , name )
group_members
( id , group_id , user_id )
I'm trying to look up the groups that a user belongs to and display that to the user. This SQL statement pretty much does the job (though there may be a better way to write it). It only returns the columns I'm concerned with which are the group's id and title.
SELECT groups.id, groups.title
FROM group_members
INNER JOIN groups
ON groups.id = group_members.group_id
WHERE user_id = $userId
How can I do this with the Zend Framework?
Finally figured out how to do it. If you've got a better way, please let me know.
$db = Zend_Db_Table::getDefaultAdapter(); //set in my config file
$select = new Zend_Db_Select($db);
$select->from('groups', array('id', 'title')) //the array specifies which columns I want returned in my result set
->joinInner(
'group_members',
'groups.id = group_members.group_id',
array()) //by specifying an empty array, I am saying that I don't care about the columns from this table
->where('user_id = ?', $userId);
$resultSet = $db->fetchAll($select);
This will return a table with only the id and title columns. The empty array() was the key to removing the columns I didn't care about. I could then do something with the result set.
foreach ($resultSet as $row) {
//do something with $row->id or $row->title
}
No need to using Join,we can use Zend_Db_Table instead for the reason about the MVC pattern. I got this idea form here,#10 by Filip.(maybe they call this "Table Data Gateway"?)