Hi I've search and try to solve the issue but failed to grab solution sorry for taking your time.
I am inserting a set of data in laravel with the query builder to insert multiple data at a time.
DB::table('table')->insert(
array(
array(
'col1' => 'data1',
'col2' => 'data1'
),
array(
'col1' => 'data2',
'col2' => 'data2'
),
)
);
Is there any way to check if exist the col1,col2 value in table if exist then update otherwise insert. I wanted to get return true or false from the query result if all data successfully update or inserted. I wanted to solve it with laravel query builder.
Thanks
As far as I know, the Laravel query builder does not support this.
You could do a raw MySQL query:
INSERT INTO table (a,b,c) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE c=c+1;
https://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
But that is very messy and MySQL specific.
Instead i would suggest you use the Eloquent ORM:
// Retrieve the flight by the attributes, or create it if it doesn't exist...
$flight = App\Flight::firstOrCreate(['name' => 'Flight 10']);
http://laravel.com/docs/5.1/eloquent#inserting-and-updating-models
Related
I have a column type JSON in database, and I'm performing an update on multiple rows.
For example, this query
Model::whereIn('id',$ids)->update([
'status' => 'canceled'
]);
And this table has another column called history (JSON type), each row already has its own history in JSON.
How do I append to each one of them? This array, for example
[
'user_id' => '144',
'action' => 'cancel',
'at' => '2021 - 08 - 30'
]
My idea and question, is there something like
Model::whereIn( 'id', $ids )->appendJson('field_name',$array);
The easiest approach could be like this:
$status = 'canceled';
$extraHistoryData = [...];
Model::whereKey($ids)->get(function ($model) use ($status, $extraHistoryData) {
$history = $model->history;
$history = array_merge($history, $extraHistoryData);
$model->update(compact('status', 'history'));
});
If you want to update all rows in a single query, the closest I can get is this thread. But It's not very likely to solve your problem.
I'm trying to write a query using CakePHP 3.7 ORM where it needs to add a column to the result set. I know in MySQL this sort of thing is possible: MySQL: Dynamically add columns to query results
So far I've implemented 2 custom finders. The first is as follows:
// src/Model/Table/SubstancesTable.php
public function findDistinctSubstancesByOrganisation(Query $query, array $options)
{
$o_id = $options['o_id'];
$query = $this
->find()
->select('id')
->distinct('id')
->contain('TblOrganisationSubstances')
->where([
'TblOrganisationSubstances.o_id' => $o_id,
'TblOrganisationSubstances.app_id IS NOT' => null
])
->orderAsc('Substances.app_id')
->enableHydration(false);
return $query;
}
The second custom finder:
// src/Model/Table/RevisionSubstancesTable.php
public function findProductNotifications(Query $query, array $options)
{
$date_start = $options['date_start'];
$date_end = $options['date_end'];
$query = $this
->find()
->where([
'RevisionSubstances.date >= ' => $date_start,
'RevisionSubstances.date <= ' => $date_end
])
->contain('Substances')
->enableHydration(false);
return $query;
}
I'm using the finders inside a Controller to test it out:
$Substances = TableRegistry::getTableLocator()->get('Substances');
$RevisionSubstances = TableRegistry::getTableLocator()->get('RevisionSubstances');
$dates = // method to get an array which has keys 'date_start' and 'date_end' used later.
$org_substances = $Substances->find('distinctSubstancesByOrganisation', ['o_id' => 123);
if (!$org_substances->isEmpty()) {
$data = $RevisionSubstances
->find('productNotifications', [
'date_start' => $dates['date_start'],
'date_end' => $dates['date_end']
])
->where([
'RevisionSubstances.substance_id IN' => $org_substances
])
->orderDesc('RevisionSubstances.date');
debug($data->toArray());
}
The logic behind this is that I'm using the first custom finder to produce a Query Object which contains unique (DISTINCT in SQL) id fields from the substances table, based on a particular company (denoted by the o_id field). These are then fed into the second custom finder by implementing where(['RevisionSubstances.substance_id IN' ....
This works and gives me all the correct data. An example of the output from the debug() statement is as follows:
(int) 0 => [
'id' => (int) 281369,
'substance_id' => (int) 1,
'date' => object(Cake\I18n\FrozenDate) {
'time' => '2019-09-02T00:00:00+00:00',
'timezone' => 'UTC',
'fixedNowTime' => false
},
'comment' => 'foo',
'substance' => [
'id' => (int) 1,
'app_id' => 'ID000001',
'name' => 'bar',
'date' => object(Cake\I18n\FrozenDate) {
'time' => '2019-07-19T00:00:00+00:00',
'timezone' => 'UTC',
'fixedNowTime' => false
}
]
],
The problem I'm having is as follows: Each of the results returned contains a app_id field (['substance']['app_id'] in the array above). What I need to do is perform a count (COUNT() in MySQL) on another table based on this, and then add that to the result set.
I'm unsure how to do this for a couple of reasons. Firstly, my understanding is that custom finders return Query Objects, but the query is not executed at this point. Because I haven't executed the query - until calling $data->toArray() - I'm unsure how I would refer to the app_id in a way where it could be referenced per row?
The equivalent SQL that would give me the required results is this:
SELECT COUNT (myalias.app_id) FROM (
SELECT
DISTINCT (tbl_item.i_id),
tbl_item.i_name,
tbl_item.i_code,
tbl_organisation_substances.o_id,
tbl_organisation_substances.o_sub_id,
tbl_organisation_substances.app_id,
tbl_organisation_substances.os_name
FROM
tbl_organisation_substances
JOIN tbl_item_substances
ON tbl_organisation_substances.o_sub_id = tbl_item_substances.o_sub_id
JOIN tbl_item
ON tbl_item.i_id = tbl_item_substances.i_id
WHERE
tbl_item.o_id = 1
AND
tbl_item.date_valid_to IS NULL
AND
tbl_organisation_substances.app_id IS NOT NULL
ORDER BY
tbl_organisation_substances.app_id ASC
) AS myalias
WHERE myalias.app_id = 'ID000001'
This does a COUNT() where the app_id is ID000001.
So in the array I've given previously I need to add something to the array to hold this, e.g.
'substance' => [
// ...
],
'count_app_ids' => 5
(Assuming there were 5 rows returned by the query above).
I have Table classes for all of the tables referred to in the above query.
So my question is, how do you write this using the ORM, and add the result back to the result set before the query is executed?
Is this even possible? The only other solution I can think of is to write the data (from the query I have that works) to a temporary table and then perform successive queries which UPDATE with the count figure based on the app_id. But I'm really not keen on that solution because there are potentially huge performance problems of doing this. Furthermore I'd like to be able to paginate my query so ideally need everything confined to 1 SQL statement, even if it's done across multiple finders.
I've tagged this with MySQL as well as CakePHP because I'm not even sure if this is achievable from a MySQL perspective although it does look on the linked SO post like it can be done? This has the added complexity of having to write the equivalent query using Cake's ORM.
If we run a query such as the following:
SELECT `user`.`user_id`
, `user`.`username`
, `profile`.`user_id`
, `profile`.`name`
, `profile`.`location`
FROM `user`
JOIN `profile`
USING (`user_id`)
WHERE `user`.`user_id` = 1;
then we get the result set:
object(ArrayObject)
private 'storage' =>
array
'user_id' => string '1'
'username' => string 'ExampleUsername'
'name' => string 'Example name'
'location' => string 'Example location'
Notice that user_id field is only returned once, even though it exists twice in the SQL query.
Is there a way to return table names as part of the result set? For example, the following result set would be desired:
object(ArrayObject)
private 'storage' =>
array
'user' => array
'user_id' => string '1'
'username' => string 'ExampleUsername'
'profile' => array
'user_id' => string '1'
'name' => string 'Example name'
'location' => string 'Example location'
I have seen this done in other frameworks (Laravel, CodeIgniter) but am not seeing the option for Zend Framework version 2 or 3.
This is just an example SQL query. We are running much more complex queries in our project where a returned associative array with table names as keys would be ideal.
I think you mean you want the keys to include table names, not database names.
IIRC there's no built-in way to do this in Zend Framework.
You can make each key distinct, but it's up to you to do this by defining column aliases:
SELECT `user`.`user_id` AS user_user_id
, `user`.`username`
, `profile`.`user_id` AS profile_user_id
, `profile`.`name`
, `profile`.`location`
FROM `user`
JOIN `profile`
USING (`user_id`)
WHERE `user`.`user_id` = 1;
This is a common problem with any database library that returns results in an associative array, not just Zend Framework and not even just PHP.
The second example you show, of fetching columns into some kind of nested data structure broken down by tables, is not supported in any database library I've ever used. How would it return the results of the following query?
SELECT user.user_views + profile.profile_views AS total_views
FROM user JOIN profile USING (user_id)
Would total_views belong under the user key or the profile key?
There are many other similar examples of SQL queries that return results that don't strictly "belong" to either of the joined tables.
Is it possible to update a timestamp (besides updated_at) and increment a column in one query? I obviously can
->increment('count')
and separately
->update(['last_count_increased_at' => Carbon::now()])
but is there an easy way to do both together.
Product::where('product_id', $product->id)
->update(['count'=> $count + 1, 'last_count_increased_at' => Carbon::now()];
Without having to query and get the count first?
You can specify additional columns to update during the increment or decrement operation:
Product::where('id',$id)
->increment('count', 1, ['increased_at' => Carbon::now()]);
It is more eloquent solution.
You can use the DB::raw method:
Product::where('product_id', $product->id)
->update([
'count'=> DB::raw('count+1'),
'last_count_increased_at' => Carbon::now()
]);
With Laravel 8 you can now achieve this in a single query to create or update on duplicate key.
$values = [
'name' => 'Something',
'count' => 1,
];
$uniqueBy = ['name'];
$update = ['count' => DB::raw('count+1')];
Model::upsert($values, $uniqueBy, $update);
If the model exists count will be incremented, if it is inserted count will equal 1. This is done on the DB level, so only one query involved.
Read more about upserts: https://laravel.com/docs/8.x/eloquent#upserts
I'm new in WordPress
I'm trying to insert on database without knowing the id, here what I'm trying to do:
$create = $wpdb->insert('wp_ito_plan', array('name' => $_POST['name'], 'tickets' => $_POST['tickets'], 'price' => $_POST['price'], 'visits' => $_POST['visits']));
and I got this error:
WordPress database error: [Duplicate entry '0' for key 'PRIMARY']
INSERT INTO `wp_ito_plan` (`name`,`tickets`,`price`,`visits`) VALUES ('asd','123','123','123')
I tried adding to the array: 'id' => $wpdb->insert_id, but stills the same.
How can I fix this? Do I need to check what is the last ID on database and then increment? There's no easiest way?
It appears as though you aren't auto incrementing the ID column so you're insert is going to overwrite an existing row. Set the ID column to auto increment and it should work fine.