I am using Laravel with a select statement to select the row with the highest id like this:
$user_id = DB::connection('mysql2')->select('SELECT MAX(id) FROM users')[0];
This returns an array with an object that looks like this:
stdClass Object ( [MAX(id)] => 11 ) 1
I have tried $object->MAX(id) and $object['MAX(id)'] but it does not seem to work.
Why are you using the RAW queries when you can utilise the power of Eloquent. You can do this
User::max('id')
This code will return the maximum value of 'id' column in 'users' table. Given that you have set up your model User. You can read more about Eloquent max at given docs link.
Dynamic attributes with usually not allowed characters can be accessed using curly brackets like this:
$object->{"MAX(id)"}
Related
Inside users table I have a json column named "agencies" that stores data as a simple array like this:
[
"0eb2edf0-50cb-44ff-a0a6-b2a104a9dc12",
"f7c748d4-8718-441e-aa69-91b890ead5ed"
],
the above is valid json. When I try to select all users that contain 0eb2edf0-50cb-44ff-a0a6-b2a104a9dc12 I get null
Is my query correct?
$users = User::whereRaw('JSON_CONTAINS(agencies->"$[*]", "0eb2edf0-50cb-44ff-a0a6-b2a104a9dc12")')->get();
is the below correct way to do write JSON select query conbsidering how I store uuids as an array inside agencies column which is defined as json?
'JSON_CONTAINS(agencies->"$[*]", "0eb2edf0-50cb-44ff-a0a6-b2a104a9dc12"
I got the idea for above select from reading: Making a Laravel 5.4 query on a JSON field containing a JSON array
but the solution in that post is different then what I am trying to do and my modification to it does not give me back any users, but instead I allways get null back.
I believe that's what you want:
$users = User::whereRaw('JSON_CONTAINS(agencies, ?)', ['0eb2edf0-50cb-44ff-a0a6-b2a104a9dc12'])->get();
It will also soon be supported with the query builder. See PR
MySQL expects a JSON string:
$users = User::whereRaw('JSON_CONTAINS(agencies, ?)',
['"0eb2edf0-50cb-44ff-a0a6-b2a104a9dc12"'])->get();
$users = User::whereRaw('JSON_CONTAINS(agencies, ?)',
[json_encode('0eb2edf0-50cb-44ff-a0a6-b2a104a9dc12')])->get();
I have an array with an object. The value of the object is a counter from my database.
I need to make a condition on that object.
var_dump($myArray);
return
array (size=1)
0 =>
object(stdClass)[62]
public 'count(videos_like.videos_like_id)' => string '5' (length=1)
I try to do it like so:
if($myArray[0]->count(videos_like.videos_like_id) == '5'){...}
But of course I get an error.
Does anyone have an idea?
I'd rather advise you to update your SQL query and replace code:
count(videos_like.videos_like_id)
to
count(videos_like.videos_like_id) AS videosCount
hence you won't have this problem.
PS: Even you don't have plain SQL and use any framework - it's definitely possible to provide alias to your count column.
Database table SITE has many columns. One of them is site_id. I need all the site_ids as an array since it has to be fed to a method which accepts only a string array.
What I tried so far is:
$sites = DB::select('select site_id from site_tab');
$sites_arr = $sites->toArray();
But this doesn't produce the result I want. I need $sites_arr to be like ['A','B','C',...]
Please suggest a way to get this done. A solution based on Eloquent is also OK for me.
Thanks
Try this:
DB::table('site_tab')->pluck('site_id')->toArray();
reference pluck
referen toArray
If you open a manual, you will see that
The select method will always return an array of results
So, there's no need to use ->toArray(), as result is already an array.
To get values as array of names you can do:
$site_ids = DB::table('site_tab')->pluck('site_id');
Using ->toArray() here is optional, as you can iterate over $site_ids (which is a Collection) with a foreach too.
I'm using laravel FindOrNew() to get an entry with two parameters, or create a new one:
$option = \App\Option::findOrNew(['user_id' => $this->id , 'option_name' => $optionName]);
I want to get an option for a user that has the name in $optionName. The problem is that it just checks for the user_id, and does not create a new one when option_name does not exist.. instead it "finds" one which does not match the $optionName value..
Can someone say what I'm doing wrong? How can I achieve this?
TL;DR:
You're using the wrong method. You're looking for the firstOrNew() method, not findOrNew().
Explanation:
The findOrNew() is an extension of the find() method, which works on ids only. It takes two parameters, the first being the id (or array of ids) to find, and the second being the columns to retrieve. It's treating the array you've passed in as an array of ids to find.
The firstOrNew() method takes one parameter: an array of attributes to search for. It will turn the array into a where clause, and then call first() on the query builder. If no results are returned, it returns a new instance with those attributes filled in.
Say I have a random zend_db_select object.
How can I perform a count on that object, so I know the amount of items that meet the query.
I tried the following:
$data->TotalRecords = $select->columns(new Zend_Db_Expr('COUNT(*)'))->query()->fetch();
But this gives me the following error:
Message: No table has been specifiedfor the FROM clause
The query by itself works fine and returns a resultset.
There's a couple of ways of specifying the columns to fetch in a Zend_Db_Select. The following two product the same SQL
$select = $db->select()
->from('myTable', array())
->columns(array('TotalRecords' => new Zend_Db_Expr('COUNT(*)')));
$select = $db->select()
->from('myTable', array('TotalRecords' => new Zend_Db_Expr('COUNT(*)')));
The from method takes a first argument, the table name, and a second argument, an array of columns to fetch. If you're using an expression, you can specify a 'key' => Expr.
It's really easy to convert a Zend_Db_Select into a SQL string for debugging or use with other functions.
echo $select; // prints SELECT COUNT(*) AS `TotalRecords` FROM `myTable`
This uses a toString method, which is called automatically by Zend_Db fetch methods:
$total = $db->fetchOne($select);
echo $total; //prints the number of rows matching the query
Where $db is an instance of Zend_Db.
Use $select->__toString() method to output your generated query and see what is wrong with it.
If u dont have a from clause in your query add From() method to your select object.
If you use Zend_Db_Select, you have to call the from method to set the table name. With a Zend_Db_Table_Select, the table is passed in the constructor, so you don't need to call from.
$select = $db->select();
$select->from(
'table_name',
array('cnt' => 'count(1)')
);
I just encountered the same issue and found out what is going wrong
the Zend_Db_Select::columns functions expects an Array instead of a Object or String (when the first parameter is an String or Object it'll probably use this as main table for the columns you give but Im not sure about that.).
Changing your code to
$data->TotalRecords = $select->columns(array(new Zend_Db_Expr('COUNT(*)')))->query()->fetch();
Will fix your issue