how convert sql to Laravel - laravel

I am new to laravel, I am having trouble converting my sql to Laravel Query.
Example
INSERT INTO table(field1, field2) SELECT 'value1', 'value2' WHERE NOT EXISTS(SELECT 1 FROM tabla WHERE campo = 'search');
this is my code
INSERT INTO siryus.presupuesto_anio (id, fk_agencia_id, anyo, estado, created_at, updated_at) SELECT 30,4,2020, 'A', '2021-04-21 10:35:01','2021-04-21 10:35:01' WHERE NOT EXISTS(SELECT 1 FROM presupuesto_anio WHERE fk_agencia_id = '4');
i want insert only if there is no field with that value. The insert is done only if there are values โ€‹โ€‹of the select, and the select will return data only if the WHERE is met.
Inside the WHERE we have a simple SELECT that verifies if the data exists in the table.
I want to convert it to example code
DB::table('presupuesto_anio') ->join('agencia','presupuesto_anio.fk_agencia_id','agencia.id') ->select('presupuesto_anio.*','agencia.descripcion') ->get();

im not understand with your questions, maybe this will help:
$check = Model::where('id', 4)->first();
if(!$check){
Model::create({
'column1' => 'value1',
'column2' => 'value2'
});
}

Related

I want the data obtained from find table1 to insert into table2 in laravel

I want the data obtained from find table1 to insert into table2
$table1= Table1::find($id);
$table2= new Table2();
without
$table2->field1 = $table1->field1;
$table2->field2 = $table1->field2;
where I have multiple fields
How do I use it? to be able to write short code
If all the fields are same in both tables, you can try,
$table1 = Table1::find($id);
// Since $table1 is an object so you have to convert it into array bcs create accepts only array
$table1 = $table1->toArray();
// Also you will have id as autoincrement in table2 so you have to remove id of record of table1 before inserting to table2.
unset($table1['id']);
//Now insert array into table2
Table2::create($table1);
Laravel has the replicate() function that will do your job.
This is how you can use it:
$table1 = Table1::find($id);
$table2 = $table1->replicate();
$table2 = $table2->toArray();
Table2::create($table2);
This function will clone your one model data into another object. If you want to change/add/replace any data from the model data then you can also add/modify it:
$table1 = Table1::find($id);
$table2 = $table1->replicate()->fill([
'field_name' => 'value' // Override any data
'new_field_name' => 'value' // Add new field data
]);
$table2 = $table2->toArray();
Table2::create($table2);
I hope that this is what you are looking for. ๐Ÿ˜„๐Ÿ˜„
mean like this?
$table1 = Table1::find($id);
Table2::create([
'field1' => $table1->field1,
'field2' => $table1->field2,
]);
if the fields in table2 are same with table1
$table1 = Table1::find($id);
Table2::create($table1->toArray());

Using same table in subquery

I am failing to convert next SQL code into laravel eloquent:
SELECT t1.template, t1.created_at
FROM sent_emails t1
where created_at = (
select max(created_at) from sent_emails t2 where t2.template = t1.template
)
group by t1.created_at, t1.template
or:
SELECT t1.template, t1.created_at
FROM sent_emails t1
JOIN
(
SELECT Max(created_at) date, template
FROM sent_emails
GROUP BY template
) AS t2
ON t1.template = t2.template
AND t1.created_at = t2.date
group by t1.created_at, t1.template
Both queries return same data set. Creating subquery in separate variable is not an option as I need multiple values to be returned from it.
I also don't know how can I set alias name if I create table using models (and not using DB::), so this is my unsuccessful try:
$sent_emails = SentEmail::where('created_at', function($query) {
SentEmail::where('template', 't1.template')->orderBy('created_at', 'desc');
})->groupBy('template', 'created_at')->get(['template', 'created_at']);
You query should be something like this (I'm not at a computer to test this, so it may require further editing)
$sent_emails = SentEmail::where('created_at', function($query) {
$query->where('created_at', SentEmail::->whereColumn('column_name', 'table.column_name')->orderBy('created_at', 'desc')->max('created_at'));
})->groupBy('template', 'created_at')->get(['template', 'created_at']);

Using IF statements in Oracle when trying to return data

How do I return data out of IF statements? I have a IF statement which is meant to return a different result dependent of the result of that statement.
IF :Value = 1 THEN
SELECT Name FROM TABLE_A
ELSEIF :Value = 2 THEN
SELECT Name FROM TABLE_B
ELSEIF :Value = 3 THEN
SELECT Name FROM TABLE_C
but this doesn't work. It expects an INTO statement in those selects. I suspect this is because Oracle can't return out of a block?
Is there a quicker way to return those select statements without creating table variables to store the data or messing around with functions?
You can do this by plain SQL:
SELECT
':Value' user_input,
CASE
WHEN ':Value' IN('a1','a2','a3')
THEN (select name from table_a)
WHEN ':Value' = 'i'
THEN (select name from table_b)
END AS output
FROM
dual
(good info about case)
If you want more than one result in your cases, then you may opt to an intelligent UNION:
SELECT t1_Col_1, t1_Col_2,'&VALUE' from TABLE_1
WHERE '&VALUE' = '1'
UNION ALL
SELECT t2_Col_1, t2_Col_2,'&VALUE' from TABLE_2
WHERE '&VALUE' = '2'
In this solution, types and number of tx_Coln must be the same.

Laravel mysqli connect 2 columns and change column name

I have 2 tables that I want to connect
table1:
id
name
table2_id
table_2:
id
name
table1 is connected with table2
When I try to select table1 and the connected row from table2 it works, but because the row names id and name are the same, it overwrites the values of table1.
How can I connect table1 with table2 and get a table1 with this rows in laravel:
id
name
table2_id
table2_name
Review the laravel documentation regarding relationships - If you set up your models as outlined here https://laravel.com/docs/5.3/eloquent-relationships you will be able to call the table2 like:
$result = Table1::find(1)->table2;
However to get the result you want you can use the ->select( function
DB::table('users')->select('name', 'email as user_email')->get();
https://laravel.com/docs/5.2/queries#selects
Something like this
public function scopetable1($query,$id){
return $query = DB::table('table1')
->select('table1.id as id','table1.name as name','table2.id as table2_id', 'table2.name as table2_name' )
->where('table1.id', '=', $id)
->leftJoin('table2', 'table1.table2_id', '=', 'table2.id')
->get();
}

Laravel query builder doesn't bind values

I am using laravel query builder like this.
$col1 = Input::get('col1','');
$col2 = Input::get('col2','');
$result = DB::table('table1')
->select('id', 'col1', 'col2', 'col3')
->whereRaw("col1 like '%?%'", [$col1])
->whereRaw("col2 like '%?%'", [$col2])
->orderBy($orderBy, $orderType) //orderBy=col1, ordeyType=ASC
->skip($ofset)->take($limit) //$ofser=0, $limit=10
->get();
I am getting nothing. If I use toSql() function. I am getting this SQL like this
select `id`, `col1`, `col2`, `col3`
from `table1` where col1 like '%?%' and col2 like '%?%'
order by `col1` ASC limit 10 offset 0
The question marks shouldn't be there. It must replace them with the values. I used this code to debug it.
Log::info(var_export(DB::getQueryLog(), true));
The Logs look like this
2 =>
array (
'query' => 'select `id`, `col1`, `col2`, `col3` from `table1` where col1 like \'%?%\' and col2 like \'%?%\' order by `col1` ASC limit 10 offset 0',
'bindings' =>
array (
0 => 'k',
1 => '',
),
'time' => 25.71,
I think bindings doesn't work pr I'm doing something wrong. Because If I try this code in database It works. (In Addition, I want to get the actual sql that send to the database. How do I do that?)
select `id`, `col1`, `col2`, `col3` from `table1`
where col1 like '%k%' and col2 like '%%'
order by `col1` ASC limit 10 offset 0
Figured it out. The ? needs to go by itself, so concatenate the % symbols to your col variables. And put your col variables in an array (assuming you're using Laravel 4)
Change:
->whereRaw("col1 like '%?%'", [$col1])
->whereRaw("col2 like '%?%'", [$col2])
To:
->whereRaw("col1 like ?", array('%'.$col1.'%'))
->whereRaw("col2 like ?", array('%'.$col2.'%'))
try
->whereRaw("col1 like '%?%'", [$col1])
->whereRaw("col2 like '%?%'", [$col2])
to
->whereRaw("col1 like '%?%'", $col1)
->whereRaw("col2 like '%?%'", $col2)

Resources