Laravel update based on other value - mysql

How can I translate this to be used within the laravel query builder ?
MYSQL
update mytable
set val = val +1
where id = 1
In laravel
$res = DB::table('mytable')
->update(['val' => ?]);
Thanks

Try:
DB::table('mytable')->where('id',1)->increment('val');
the increment method accept as second parameter the amount to sum, if you need to do val = val + 2 you can use ->increment('val', 2).
See this as reference: https://laravel.com/api/5.3/Illuminate/Database/Eloquent/Builder.html#method_increment

In cases where you're doing a more complicated calculation than an increment, you can also do something like this:
DB::table('mytable')->where('id',1)->update(['val' => DB::raw('val * 3')]);
Be careful with DB::raw - it's not going to escape user input for you.

Related

Mysql) when i using user-defined variable , SQL explain use type "ALL"

When i using user-defined variable , i want to use 'index' like 'ref..';
for example,
SET #company_code = "A002";
select *
from product_in_out
where company_code = #company_code
and product_date = "2022-04-13"
and out_type = "Q"
;
above result like this,
[enter image description here][1]
for using SQL index, i've tested that variable to plain text like "A002".
at that time, SQL use index like 'ref'
select *
from product_in_out
where company_code = "A002"
and product_date = "2022-04-13"
and out_type = "Q"
;
if so, is there any good way to use valiable for using mysql Index?!?!
As a workaround, add this composite index:
INDEX(out_type, product_date, company_code)
(I assume product_date is of datatype DATE.)

Attempting to add a prefix to a column in SQL Server 2008

I'm trying to add prefix with a condition using 'from' x table then using where to specify the id
For example:
UPDATE tablenameX
SET columnnameX = 'prefix' + columnnameX
FROM tablenameY
WHERE columnnameY = 'id'
I really don't see wheres the issue it refuses to read after columnnameX, what I mean by that is it would execute with no issue, however it ignores the argument I'm trying to use and it applies to every column entry.
I've used a lot of this type of simplistic SQL commands with no issue, I have no idea how to fix it nor do I have the knowledge how to build something that's more complex in nature - I'm a newbie so bear with me.
I'm not sure what the join criteria are because you haven't told us how X and Y are related, but a correlated join looks like this:
UPDATE x
SET x.columnnameX = 'prefix' + x.columnnameX
FROM dbo.tablenameX AS x
INNER JOIN dbo.tablenameY AS y
ON y.< ??? something ??? > = x.< ??? something ???>
WHERE y.columnnameY = 'id';
Or like this:
UPDATE x
SET x.columnnameX = 'prefix' + x.columnnameX
FROM dbo.tablenameX AS x
WHERE EXISTS
(
SELECT 1 FROM dbo.tablenameY AS y
WHERE columnnameY = 'id'
AND y.< ??? something ??? > = x.< ??? something ???>
);

Can I increase an existing field in MySQL by one using gorm? Without using raw SQL

If I use the raw SQL, it would be "UPDATE table_name SET field1 = field1 + 1 WHERE id = an_id_val";
How can I achieve the same thing with func chain calls like db.Update() or db.Save() etc.
Thanks in advance.
You could use a sql expression
DB.Model(&your_model).UpdateColumn("field1 ", gorm.Expr("field1 + ?", 1))
http://gorm.io/docs/update.html

Laravel 4 - SQL query to Laravel Eloquent query

I'm working on a school project and I'm trying to get a query working.
SELECT *
FROM `ziekmeldingen` AS a
WHERE NOT EXISTS
(SELECT *
FROM `ziekmeldingen` AS b
WHERE `ziek` = 1
AND a.personell_id = b.personell_id)
Name of the model: ZiekmeldingenModel
I tried 2 things, both dont work ->
$medewerkers = ZiekmeldingenModel::whereNotExists(function($query)
{
$query->select()->from('ziekmeldingen AS b')->where('ziek', '=', '1')->where('ziekmeldingen.personell_id', '=', 'b.personell_id');
})->get();
return $medewerkers;
And
$medewerkers = ZiekmeldingenModel::raw('SELECT * FROM `ziekmeldingen` as a WHERE NOT EXISTS ( SELECT * FROM `ziekmeldingen` as b WHERE `ziek` = 1 AND a.personell_id = b.personell_id)')->get();
Both of them give back all the results from the table while it should only give back 1 result (I've tested the original query, it works).
EDIT: Forgot to mention I'm using relationships in the model. So the raw solution probably won't work anyway
Found the answer. Had to use a combo of both the things I tried.
$medewerkers = ZiekmeldingenModel::select()
->from(DB::raw('`ziekmeldingen` AS a'))
->whereNotExists(function($query){
$query->select()
->from(DB::raw('`ziekmeldingen` AS b'))
->whereRaw('`ziek` = 1 AND a.personell_id = b.personell_id');
})->get();
return $medewerkers;
Thanks for any help and effort.
Definitely no need for select(). Also no raw in from or whereRaw needed.
The only unusual thing here is raw piece in the where, since you don't want table.field to be bound and treated as string. Also, you can use whereRaw for the whole clause in case you have your tables prefixed, otherwise you would end up with something like DB_PREFIX_a.personell_id, so obviously wrong.
This is how you do it:
$medewerkers = ZiekmeldingenModel::from('ziekmeldingen AS a')
->whereNotExists(function ($q) {
$q->from('ziekmeldingen AS b')
->where('ziek', 1)
->where('a.personell_id', DB::raw('b.personell_id'))
// or:
// ->whereRaw('a.personell_id = b.personell_id');
})->get();
Use the take() method though if you're not ordering your results the record you get back could be any of the results.
$medewerkers = ZiekmeldingenModel::raw('SELECT * FROM `ziekmeldingen` as a WHERE NOT EXISTS ( SELECT * FROM `ziekmeldingen` as b WHERE `ziek` = 1 AND a.personell_id = b.personell_id)')->take(1)->get();

MySQL: How can fetch SUM() of all fields in one Query?

I just want somthing like this:
select SUM(*) from `mytable` group by `year`
any suggestion?
(I am using Zend Framework; if you have a suggestion using ZF rather than pure query would be great!)
Update: I have a mass of columns in table and i do not want to write their name down one by one.
No Idea??
SELECT SUM(column1) + SUM(column2) + SUM(columnN)
FROM mytable
GROUP BY year
Using the Zend Framework's Zend_Db_Select, your query might look like
$db = Zend_Db::factory( ...options... );
$select = $db->select()
->from('mytable', array('sum1' => 'SUM(`col1`)', 'sum2' => 'SUM(col2)')
->group('year');
$stmt = $select->query();
$result = $stmt->fetchAll();
Refer to the Zend_Db_Select documentation in the ZF manual for more.
EDIT: My bad, I think I misunderstood your question. The query above will return each colum summed, but not the sum of all of the columns. Rewriting Maxem's query so that you can use it with a Zend Framework DB adapter, it might look like
$sql = '<insert Maxem's query here>';
$result = $db->fetchAll($sql);
You might choose to use fetchCol() to retrieve the single result.
It sounds like you don't want to explicitly enumerate the columnn and that you want to sum all the columns (probably excluding the year column) over all the rows, with grouping by year.
Note that the method Zend_Db_Table::info(Zend_Db_Table_Abstract::COLS) will return an array containing the columns names for the underlying table. You could build your query using that array, something like the following:
Zend_Db_Table::setDefaultAdapter($db);
$table = new Zend_Db_Table('mytable');
$fields = $table->info(Zend_Db_Table_Abstract::COLS);
unset($fields['year']);
$select = $table->select();
$cols = array();
foreach ($fields as $field){
$cols[] = sprintf('SUM(%s)', $field);
}
$select->cols(implode(' + ', $cols));
$select->group('year');
I have not tested the specific syntax, but the core of the idea is the call to info() to get the fields dynamically.
Done in ZF rather than pure query and you don't have to write the name of the columns one by one.
(I assume you are extending Zend_Db_Table_Abstract)
If you're asking how to write
select SUM(*) from `mytable` group by `year`
This is how it is done:
public function sumOfAllFields(){
return $this->fetchAll( $this->select()->from('mytable','SUM(*)')->group('year') )->toArray();
}
Or not using Zend...
function mysql_cols($table){
$sql="SHOW COLUMNS FROM `".$table."`";
$res=mysql_query($sql);
$cols=array();
while($row=mysql_fetch_assoc($res))$cols[]=$row['Field'];
return $cols;
}
$cols=mysql_cols("mytable");
$select_sql=array();
foreach($cols as $col){
$select_sql[]="SUM(`".$col."`)";
}
$select_sql=implode('+',$select_sql);
$sql="select (".$select_sql.") from `mytable` group by `year`";