Insert data into two tables, one depend on another - codeigniter

For example I have such structure in database:
table1:
[id]
[content]
table2:
[id]
[table1_id]
and I want insert some data at the same time into this two tables, but the problem is with [table1_id] which is primary key from table1. How can I insert it?

In order to insert the primary key of table 1 into table 2, code igniter has built in helper functions to help with this task.
//prepare data for table 1
$data = array(
'conent' => 'My content',
);
//insert into table 1
$this->db->insert('table1',$data);
//prepare data for table 2
$data = array(
'table1_id' => $this->db->insert_id(),
);
//insert into table 2
$this->db->insert('table2',$data);

As you are referring table1_id in table2 so u must insert your table1 fields first. Then you can insert into table2.
Here is what you can do in your controller
public function insert(){
$data['table1_data']=$this->ur_model->insert_table1();
$latest_id=$this->ur_model->get_latest_id();
$data['table1_data']=$this->ur_model->insert_table2($latest_id);
}
in your model
function insert_table1(){
$data=array(
'content'=>$this->input->post('content')
);
$this->db->insert('table1',$data);
//better return true on success
}
public function get_latest_id(){
$sql=$this->db->query("SELECT MAX(id) as id FROM table1");
return $sql->row_array();
}
function insert_table2($table1_id){
$data=array(
'content'=>$this->input->post('content'),
'table1_id'=>$table1_id['id']
);
$this->db->insert('table2',$data);
}
So that you will always get latest id inserted into table1_id.

Related

Laravel get column name using child table with eager loading

I want to fetch the data from profile table using a child table of other parent table.
Here is the tables
Profile table
id
profile_name
Transaction table
id
transaction_name
Sub transaction table
id
transaction_id
profile_id
Now i want to get the profile name from transaction model using eager loading . i tried has one Though relationship in transaction model but returning null
Here is my relationship in Transaction model
public function profileName()
{
return $this->hasOneThrough(
Profiler::class,
SubTransaction::class,
'profile_id',
'id',
'id',
'transaction_id',
);
}
Here is where i am trying to fetch from transaction controller
$options = Transaction::with([
'profileName:id,profile_name as profileName',
])
->get();
It returns null because I think you have a little problem about matching between foreign keys and local keys. You could try the following code:
return $this->hasOneThrough(
Profiler::class, //Final model we wish to access
SubTransaction::class, //The name of the intermediate model
'transaction_id', //Foreign key on sub_transaction table
'id', //Foreign key on profile table
'id', //Local key on transaction table
'profile_id', //Local key on sub_transaction table
);
If you have any problem, tell me.

Issue while trying to search using whereBetween in Laravel Eloquent

I have 2 database tables in MySQL below.
Table - 1
CREATE TABLE `tblaccount` (
`account_id` mediumint(8) UNSIGNED NOT NULL,
`account_number` varchar(100)
)
ALTER TABLE `tblaccount`
ADD PRIMARY KEY (`account_id`);
Table - 2
CREATE TABLE `tblcollectoractions` (
`collector_action_id` mediumint(8) UNSIGNED NOT NULL,
`account_id` mediumint(8) UNSIGNED DEFAULT NULL,
`pay_date` date DEFAULT NULL
);
ALTER TABLE `tblcollectoractions`
ADD PRIMARY KEY (`collector_action_id`),
ADD KEY `tblcollectoractions_account_id_foreign` (`account_id`);
I have a query below. It joins records in both tables on the basis of account_id. It also filters those accounts in tblcollectoractions table where pay_date lies between start and end date.
Here is my Laravel Eloquent Query. AccountModel is related to tblaccount and ActionModel is related to tblcollectoractions.
$query = (new AccountModel())->newQuery();
$data->whereIn("account_id", function($query) use($inputs) {
$query->select('account_id')->from(with(new ActionModel)->getTable())
->whereBetween('pay_date', [$inputs["from_pay_date"], $inputs["to_pay_date"]]);
});
But, this shows me all the records from table tblcollectoractions. I meant, it does not filter on the basis of start and end date.
Am I missing anything?
This is the most Eloquent way to do this, checking if the $inputs variable is set
$data = AccountModel::query()
->with([
'actions' => function($query) use ($inputs) {
if ($inputs['from_pay_date']) {
$query->whereBetween('pay_date', [
$inputs['from_pay_date'],
$inputs['to_pay_date']
]);
}
}
])
->has('actions')
->get();
the models should look something like this:
AccountModel.php
class AccountModel extends Model
{
protected $guarded = ['id'];
public function actions()
{
return $this->hasMany(ActionModel::class, 'account_id', 'account_id');
}
}

How to copy data from one table to another “EXCEPT” one field Codeigniter

How can I use codeigniter to copy all data of table1 to table2 except the primary key of table1. table1 and table2 have the same structure.
I try this :
$query = $this->db->get_where('table1',array('patient_id'=>$this->input->post('patient_id')));
foreach ($query->result() as $row) {
$this->db->insert('table2',$row);
}
It works but the primary key of table1 is inserted as well.
How can I ignore the primary key on table1 ?
Thanks in advance
Assuming patient_id is the primary key in question, you can remove the data from the result object with unset.
$query = $this->db->get_where('table1',array('patient_id'=>$this->input->post('patient_id')));
foreach ($query->result() as $row) {
unset($row->patient_id);
$this->db->insert('table2',$row);
}

cakePHP 3 save data in Many to Many relationship

I have Employees and Complexes in a Many to many relationship.I have used the
bake console to generate models, controllers... for Employees and Complexes tables.
My questions is :
-Since I have in my BD The table "complexes_employees", do I have to bake also Model
and controller for this Table too or cakePHP is able to know that it contains the
two foreign keys of Employees and Complexes.
Second question :
-How can I save my data in this Three tables. for my app I have to save employees
per Complex .
// Employees Controller
public function addEmpPerComplex($id_complex){
$emp = $this->Employees->newEntity();
if ($this->request->is('post')) {
$employee = $this->Employees->patchEntity($employee, $this->request->data, ['associated'=>['Complexes._joinData']] );
//here I need to insert the record that contains the employee data in Employees Table
// then I need to insert in "complexes_employees" the ID of Complex sended in parametre of this function and the ID of the new Employee
Thanks for helping me
Do I have to bake also Model and controller for this Table?
No, CakePHP will use the abstract Table class. However, if you need extra information for this relationship, then you will need to create a join model. Check http://book.cakephp.org/3.0/en/orm/associations.html#using-the-through-option
How can I save my data in this Three tables?
As long as your data has the id of a related entity, it will automatically be saved both entity and relation:
$data = [
//employee data,
'complexes' => [
['id' => $id_complex]
]
]
$this->Employees->patchEntity($employee, $data, [
'associated' => ['Complexes']
]);
/*
Saves both the new Employee and the relation
(employeed id and complex id in complexes_employees)
*/
$this->Employees->save($employee);
For more information: http://book.cakephp.org/3.0/en/orm/saving-data.html#saving-belongstomany-associations

How to write data to "sales_flat_order_payment" table in a custom field?

In my custom module, I changed the table sales_flat_order_payment and sales_flat_quote_payment and added two new fields:
$installer->run("
ALTER TABLE `{$installer->getTable('sales/quote_payment')}` ADD `ep_entity` VARCHAR( 255 ) NOT NULL ;
ALTER TABLE `{$installer->getTable('sales/quote_payment')}` ADD `ep_reference` VARCHAR( 255 ) NOT NULL ;
ALTER TABLE `{$installer->getTable('sales/order_payment')}` ADD `ep_entity` VARCHAR( 255 ) NOT NULL ;
ALTER TABLE `{$installer->getTable('sales/order_payment')}` ADD `ep_reference` VARCHAR( 255 ) NOT NULL ;
");
In my model , there is the following function that will make the client redirect to my custom success page:
public function getOrderPlaceRedirectUrl() {
return Mage::getUrl('mymodule/mymethod/success', array('_secure' => false));
}
In the controller, there is the following function:
public function successAction()
{
$incrementId = Mage::getSingleton('checkout/session')->getLastRealOrderId();
$order = Mage::getModel('sales/order')->loadByIncrementId($incrementId);
$order->setEpReference('123456');
$order->save();
}
The problem is that no data is recorded on the sales_flat_order_payment table in the ep_reference field.
How to write data to sales_flat_order_payment table in a custom field?
I don't want to add custom fields in the form, the custom field is automatically populated after the payment is completed.
I found the solution:
public function successAction()
{
$incrementId = Mage::getSingleton('checkout/session')->getLastRealOrderId();
$order = Mage::getModel('sales/order')->loadByIncrementId($incrementId);
$payment = $order->getPayment();
$payment->setEpReference('123456');
$paymentQuote = $quote->getPayment();
$paymentQuote->setEpReference('123456');
$paymentQuote->save();
$order->save();
}

Resources