this my code
DB::connection('mysql2')->insert('INSERT INTO pm_booking_service (id_booking, title, qty, amount) VALUES ('2','restaurant','1','27')' );
I don't know how to do insert Using Multiple Database Connections
but select is working fine
$bookings = DB::connection('mysql2')->select('select * from pm_booking');
When you have a string that starts with a single quote you need to escape any single quotes it contains otherwise they are interpreted as closing the string.
Use parameters to not need to quote the values manually:
DB::connection('mysql2')
->insert('INSERT INTO pm_booking_service (id_booking, title, qty, amount) VALUES (?,?,?,?)', [2,'restaurant',1,27]);
An example of this can be found in the docs as well
This can be rewritten in the query builder as :
DB::connection('mysql2')->table('pm_booking_service')
->insert([
'id_booking' => 2,
'title' => 'restaurant',
'qty' => 1,
'amount' => 27
]);
Update statements are also written similarly:
DB::update(
'update pm_booking_service set qty = ? where id = ?',
[100, 2]
);
This also can be written in the query builder as:
DB::connection('mysql2')->table('pm_booking_service')
->where('id', 2)
->update([ 'qty' => 100 ]);
Related
I trying to insert a row in codeigniter and row inserted.
Problem is all row inserted properly but in sql bighint(11) field inserted 0.
I checked properly in array value given.
$data = [
'sku' => $POST['rec1'],
'pruch_price' => $POST['rec2'],
'sell_price' => $POST['rec3']
];
$model->insert ($data);
you should use $_POST[] instead of $POST.
But better yet, don't send $_POST directly to the models, instead use the post request provided by Codeigniter 4.
$data = [
'sku' => $this->request->getPost('rec1'),
'pruch_price' => $this->request->getPost('rec2'),
'sell_price' => $this->request->getPost('rec3')
];
$model->insert($data);
The 2 models involved are JobRequest and StationJob. Really their relationship is oneToMany. I have a relationship set up for this $jobRequest->stationJobs().
Further to this I need a hasOne relationship latestStation, based on the same model. I need this relationship to filter my collection of JobRequests based on whether the JobRequest has a latestStation equal to a specified station.
I am expecting to get an empty list of JobRequests because I know the latestStation is equal to id 3 and I am filtering for id 2. Instead I get the jobRequest, with latestStation id 3 even though I am filtering for 2.
Relationship
public function latestStationTest()
{
return $this->hasOne(StationJob::class)->whereNotNull('finished')->latest();
}
Controller
$stationId = $request->station_id;
$jobRequests = JobRequest::with(['latestStationTest'])->whereHas('latestStationTest', function($query) use ($stationId) {
$query->where('station_id', $stationId);
})->get();
Query Result
[2020-10-17 07:39:07] local.INFO: array (
0 =>
array (
'query' => 'select * from `job_requests` where exists (select * from `station_jobs` where `job_requests`.`id` = `station_jobs`.`job_request_id` and `station_id` = ? and `finished` is not null)',
'bindings' =>
array (
0 => 2,
),
'time' => 1.0,
),
1 =>
array (
'query' => 'select * from `station_jobs` where `finished` is not null and `station_jobs`.`job_request_id` in (1) order by `created_at` desc',
'bindings' =>
array (
),
'time' => 0.5,
),
)
I've tried...
Switching with() before or after whereHas makes no difference.
adding ->where() to with() selects the StationJob with the specified id, instead of checking if the latestStation id is equal to the specified id.
i am using DB to store values in database.
i have "course fees" column i what to "increment" the "course_fees" value in column.
for example
DB::table('student')->where('registration_id','=', $request->registration_id)->increment(['course_fees' =>$request->course_fees]);
this code increment the inserted value
how can i modified below code for increment "course_fees" value like above
DB::table('student')->where('registration_id','=', $request->registration_id)->update(['payment_date' => $request->payment_date,'balance_fees' => $request->balance_fees,'course_fees' =>$request->course_fees]);
You cannot use this method to increment multiple fields. You can use:
$studentQuery = DB::table('student')->where('registration_id','=', $request->registration_id);
(clone $studentQuery)->increment('payment_date',$request->payment_date);
(clone $studentQuery)->increment('balance_fees', $request->balance_fees);
(clone $studentQuery)->increment('course_fees', $request->course_fees);
but this way you will run 3 database queries to update.
But if you are sure there is exactly single record found for registration_id you can do it like this:
$student = DB::table('student')->where('registration_id','=', $request->registration_id)->first();
$student->update([
'payment_date' => $student->payment_date + $request->payment_date,
'balance_fees' => $student->balance_fees + $request->balance_fees,
'course_fees' => $student->course_fees + $request->course_fees
]);
EDIT
If you want to increment only course_fees column and want to update other 2 columns from input you can use:
DB::table('student')->where('registration_id','=', $request->registration_id)
->increment('course_fees' , $request->course_fees, [
'payment_date' => $request->payment_date,
'balance_fees' => $request->balance_fees
])
This is documentation about increment/decrement methods.
increment()/decrement() can take 3 parameters: $column, $amount, $extra.
$column is the field that you want to increment
$amount is by how much you want to increment the field by
$extra is an array of attributes that you also want to update in the query.
If you don't pass an amount the default for $amount is 1.
To achieve what you're after you could do:
DB::table('student')
->where('registration_id', $request->registration_id)
->increment('course_fees', $request->course_fees, [
'payment_date' => $request->payment_date,
'balance_fees' => $request->balance_fees,
]);
I have two databases (one in Oracle and one mySQL) and I somehow need to join the data.
The following query works:
$qry = oracleTableName::find()
->with('mysqlTableName')
->asArray()
->all();
and returns the following layout:
[0]=> array(
[id] => 1
[name] => test
[mysqlID] => 7
[mysqlTableName] => array(
[id]=>7
[score]=>1
)
)
However, if I use the select statement, it fails, (saying that the column mysqlTableName.id is an invalid identifier):
$qry = oracleTableName::find()
->with('mysqlTableName')
->select([
'oracleTableName.id as OracleID',
'mysqlTableName.id as MysqlID',
'mysqlTableName.score as Score'
])
->asArray()
->all();
How can I select from both databases (or "access" the mysql result) so that I have one output i.e.:
[0]=>array(
[OracleID]=>1
[MysqlID]=>7
[Score]=>3
Thank you
UPDATE
Here is the actual query and outputs:
NOTE: in this example, the table "MapInvestorToOpportunity" is mysql and the table "INVESTOR" is Oracle
This works fine:
$performance= MapInvestorToOpportunity::find()
->with('investor')
->andWhere(['fk_opportunityID' => $this->fk_opportunityID])
->limit(5)
->asArray()
->all();
And yields the following output:
Array
(
[0] => Array
(
[id] => 43797
[uid] => 0451/0258_DD45834-99207
[fk_opportunityID] => 3
[status] => 1
[fk_investorID] => 99207
[investor] => Array
(
[INVESTOR_ID] => 99207
[COUNTRY_ID] => US
[PRIMARY_INSTITUTION] => DD71233
I can clearly see the country ID. However, as soon as I select the country ID it fails:
$performance= MapInvestorToOpportunity::find()
->with('investor') // or ('investor INVESTOR')
->andWhere(['fk_opportunityID' => $this->fk_opportunityID])
->select([
'fk_opportunityID',
'fk_investorID',
'map_investor_to_opportunity.INVESTOR_ID',
'COUNTRY_ID', // or 'INVESTOR.COUNTRY_ID'
])
->limit(5)
->asArray()
->all();
Column not found: 1054 Unknown column 'INVESTOR.COUNTRY_ID' in 'field list'
The SQL being executed was: SELECT `fk_opportunityID`, `fk_investorID`, `INVESTOR`.`COUNTRY_ID` FROM `map_investor_to_opportunity` WHERE `fk_opportunityID`='3' LIMIT 5
My understanding is that it is not possible to join the data in a query because it is two different databases. However, I just wanted to make absolutely sure... it seems a little crazy considering the array output clearly shows the data from the Oracle database
Many thanks
I don't think it is possible to create JOIN between two completely separate DBMS. with() will register eager loading rules, but it will not create actual join between two tables - it will perform two separate queries to obtain necessary models.
To create actual join you should use joinWith() instead of with().
$qry = oracleTableName::find()
->joinWith('mysqlTableName')
->select([
'oracleTableName.id as OracleID',
'mysqlTableName.id as MysqlID',
'mysqlTableName.score as Score'
])
->asArray()
->all();
But this will most likely fail, since there is no support for cross-DB joins.
Probably the best what you could get is to query results separately and combine them at PHP level.
You should just add a table identifier after the table name.
$qry = oracleTableName::find()
->with('mysqlTableName msql')
->select([
'oracleTableName.id as OracleID',
'msql.id as MysqlID',
'msql.score as Score'
])
->asArray()
->all();
The reason for this is, the with clause accepts relation name, not Table name, which might be slightly, but enough different. If this doesn't work, please comment with the result of this query and I will edit the answer accordingly
$qry = oracleTableName::find()
->with('mysqlTableName msql')
->select([
'oracleTableName.id as OracleID',
'msql.id as MysqlID',
'msql.score as Score'
])
->createCommand()->rawSql;
I want to use composite key in ActiveRecord.
I got two tables.
Quotes and Comments.
Quotes contains pk - id;
Comments pk is composite - module, section, cid
module - module name, where comments come from.
section - section of this module
cid - identificator, in this situaction this is id of quote.
In comments I defined primary key like so.
public function primaryKey()
{
return array('module', 'section', 'cid');
}
Next one, I want to get those records, what related to quotes.
So, in Quotes I declared relation:
'comments' => array(self::HAS_MANY, 'Comment', 'module, section, cid', 'params' => array(
':ypl0' => '"quotes"',
':ypl1' => '"quote"',
':ypl2' => 'id'
)),
The required result is:
SELECT * FROM quotes q
LEFT JOIN comments c ON (c.cid = q.id AND module = "quotes" AND section = "quote")
WHERE c.id IS NULL
SQL is working, relation - not. What I'm doing wrong?
Try the following untested code
'comments' => array(self::HAS_MANY, 'Comment', 'cid','condition'=>'module=:param1 AND section=:param2','params' => array(':param1' => 'quotes',':param2' => 'quote',)),