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.
Related
I have an array like this and it has 120 elements in it
`array (size=120)
0 =>
array (size=8)
'name' => That the quick brown fox jumps over the lazy - 7' (length=53)
'url' => string 'google.com/zyx' (length=134)
'category' => string 'search-engine' (length=6)
1 =>
array (size=8)
'name' => string 'Mr. john brandy gave me a wall nut of quite' (length=67)
'url' => string 'yahoo.com/dzxser' (length=166)
'category' => string 'indian' (length=6)`
I want to insert them to my bookmark table which model I have created and I want to make sure duplication doesn't occur. I have found this https://laravel.com/docs/5.4/eloquent#other-creation-methods specially firstOrCreate method.
I assume I have to use foreach but I am not sure how. Can anyone help me with some workaround.
Actually you don't need firstOrCreate, you need updateOrCreate. Checking Laravel Other Creation methods You will find that method.
Say that array is in $alldata:
foreach($alldata as $data) {
MyModel::updateOrCreate($data); //the fields must be fillable in the model
}
This will run update/or create of 120 queries while cycling through the loop. The advantage is that, you cannot have a duplicate, rather if there is a repetition, its only going to perform an update to the table.
However the best way to ensure that there is no duplication in whatever way the data comes is to set it up when making your database table. You can set unique constraints on many fields if thats your case.
If you don't want duplication to occur when inserting array of records then all you have to do it set a constraint making sure fields are unique.
If you're using migrations to create databse schema you can use something like this: $table->string('name')->unique();
Now for example, this will make sure that 'name' column data is
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)"}
In CakePHP3, there is a ORM that helps with building queries.
From the documentation, I can see that
$query = $articles->find(); // build a query that has not run yet
$query->where(['id' => 1]); // Return the same query object
So in this case, I want the string
WHERE `articles`.`id` = 1
After much googling, I found out that there is a way to return just the where clause of a query object.
$query->where(['id' => 1])->clause('where'); // Return the where clause in the form of a QueryExpression
More googling leads me to find out how to get the QueryExpression to spit out string representation
$query->where(['id' => 1])->clause('where')->sql($valueBinder); // Return the where clause in string format
Here is my problem. I don't know what the $valueBinder is supposed to look like. I don't know how to initialize it.
I am also happy not to use ValueBinder as long as I can get the where clause in string format using CakePHP 3 ORM and in the right SQL dialect. Please assume I am using MySQL.
Please advise.
EDIT
I tried to use $query->valueBinder() as the $valueBinder.
It is empty and does not contain the associated c:0 to the value 1.
To directly answer your question, you can get the SQL for any clause this way:
$binder = new \Cake\ORM\ValueBinder();
$query->clause('where')->sql($binder);
That will return the SQL with the correct placeholders, not with the values to be used. The values live in the $binder variable and are used for statement objects.
As I can see, you only wanted to preserve the internal structure of the where clause to pass it to another query in a different request. Your solution is fine, but I'd like to add that you can also encode a full conditions tree from an existing query:
$where = serialize($query->clause('where'));
$anotherQuery->where(unserialize($where)); // A query in another request
In any case, you need to be careful with what you are unserializing as taking it directly from user input will certainly lead to security problems.
You can choose to omit this param if you like. Please see http://api.cakephp.org/3.0/class-Cake.Database.Query.html#_sql
In addition, you can use the Query member function traverse($visitor, $parts) to isolate the where clause. $visitor is a function that takes a value and a clause. You define the behavior of $visitor. $parts is an array of clause names. I suggest passing array('where') into this param.
My workaround is that I store the conditions in json string format.
Using the same example, what I do is
$data['conditions'] = json_encode(['Articles.id' => 1]); // encode into JSON string
$this->DynamicRules->patchEntity($dynamicRule, $data); // use in edit action of DynamicRulesController
then when I need to reuse the conditions, I do:
$articlesTable = TableRegistry::get('Articles');
$query = $articlesTable->find(); // new query for Articles
$rule = json_decode($dynamicRule->conditions, true); // get back the conditions in associative array format
$query->where($rule); // re-assign the conditions back
This got me what I ultimately wanted.
Simple Propel reusing query is not working here, despite my code is similar to the example on Propel website. Is this a bug or my bad?
$q = MashupSettingQuery::create()->filterByMashup($this);
var_dump($q->count(), $q->findOneByKey('redirect_uri'), $q->count());
Output is:
int 5
object(MashupSetting)[28]
protected 'startCopy' => boolean false
protected 'id' => int 9
protected 'key' => string 'redirect_uri' (length=12)
int 1
that is, resusing is not working because count() first returns 5 and then 1.
Even using MashupSettingQuery::create()->filterByMashup($this)->keepQuery(true) didn't fix the problem.
I think it's normal because just before the second count you make a findOneByKey query, and so the second count just count how many objects this specific query return.
And your query return just one object, obviously because it's a findOneByKey.
So I am writing a small PHP framework for fun, and I have come to a point where I need to format an arbitrary query result into this format:
Array(<br>
[tablename]<br>
[fieldname] => value<br>
[fieldname] => value<br>
[tablename]<br>
[fieldname] => value);<br>
<br>
If I was doing this in mysql, I would simply do it this way: $tmp[mysql_field_table][mysql_field_name] = $value. But I chose to do this project using mysqli, and I can't seem to find an equivalent for mysql_field_table() so I can determine the table for each individual value. What is the ideal method for gaining this result?
Look at the example here in the manual; the return value of the function documented is an object with a member called 'table'.
This gives you what you need.