I am using Laravel Excel and I need to get id of imported rows during import.
code
public function model(array $row)
{
$link = new Link([
'site_name' => $row['site_name'],
]);
$name = explode('-', $row['site_name']);
$site = Site::whereIn('name', $name)->pluck('id');
$link->sites()->sync($site, false); // this `$link` can't get id of imported row
return $link;
}
Error
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'link_id'
cannot be null (SQL: insert into link_sites (link_id, site_id)
values (?, 14))
Any idea?
Solved
I've changed my function to use onEachRow and it's working now.
public function onRow(Row $row)
{
$rowIndex = $row->getIndex();
$row = $row->toArray();
$link = Link::create([
'site_name' => $row['site_name'],
]);
$name = explode('-', $row['site_name']);
$site = Site::whereIn('name', $name)->pluck('id');
$link->sites()->sync($site, false);
}
Document
Related
I'm trying to get all item series from a deposit but the deposit id is on a related table. On this function i'll list all the series between two sequences requested
public function getSeries($params = [])
{
$data = collect($params);
$inicio = $data->only('serie_in');
$fim = $data->only('serie_fi');
$depOrigem = $data->only('id_origem');
$series = [];
for($i = $inicio; $i <= $fim; ++$i)
{
$item = Item::leftJoin('produtoItem', 'produtoItem.id', '=', 'item.id_produtoItem')->where('serie', $i)->where('produtoItem.id_deposito', $depOrigem)->first();
if(empty($item))
{
$status = 'I';
}
else
{
$status = $item->status;
}
$series[] = [
'serie' => $i,
'status' => $status
];
}
$result = [
'status' => true,
'data' => $series
];
return $result;
}
This is the error message, i'm thinking that must be as sintax error, but a dont realy know what? Can you help me?
Illuminate\Database\QueryException: SQLSTATE[HY000]: General error: 2031 (SQL: select * from item left join produtoItem on produtoItem.id = item.id_produtoItem where serie = ? limit 1) in file /usr/share/nginx/html/controleestoque/vendor/laravel/framework/src/Illuminate/Database/Connection.php on line 671
I was calling the request on my controller without a validator, so i rewrite the getSeries method.
public function getSeries(Request $request){
$data = $request->only(['serie_in', 'serie_fi', 'id_origem']);
$result = $this->produto_service->getSeries($data);
return response()->json($result);
}
And my function work it !
I am doing update in zend which in some cases doesn't update all the fields, the fields that are not updated become null as if we are doing an add.
This is the code from the Controller
$result = $theuserModel->updateUserTest(
$id,
$this->getRequest()->getPost('user_name'),
/*some code*/
$this->getRequest()->getPost('user_postee')
);
if ($result) {
$this->view->notif = "Successfull Update";
return $this->_forward('index');
}
The corresponding model
public function updateUserRest($id, $nom,$poste)
{
$data = array(
'user_name' => $nom,
'user_postee' => $poste
);
$result=$this->update($data, 'user_id = '. (int)$id);
return $result;
}
I do an update for user_name only I found that the old value of user_postee got deleted and replaced by the default value (initial value which we get at the time of creation) for example null.
Thanks in advance!
I have done this changes (bad solution) If anyone has another one optimised
->Controller
if($this->getRequest()->getPost('user_name')){
$resultname=$userModel->updateUserName($id,$this-
>getRequest()->getPost('user_name'));
}
if($this->getRequest()->getPost('user_postee')){
$resultpostee=$userModel->updateUserPoste($id,$this-
>getRequest()->getPost('user_postee'));
}
if ($resultname|| $resultpostee){
$this->view->notif = "Mise à jour effectuée";
return $this->_forward('index');
}
-> Model
public function updateUserName($id, $name)
{
$data = array(
'user_name' => $name
);
$result=$this->update($data, 'user_id = '. (int)$id);
return $result;
}
public function updateUserPostee($id, $postee)
{
$data = array(
'user_postee' => $poste
);
$result=$this->update($data, 'user_id = '. (int)$id);
return $result;
}
that is complete correct response of update in Zend Db Table.
I believe your assumption is if the value of 'user_postee' is null then it should not be updated into the database, am I correct.
The answer is they will update the new value of "NULL" into the database.
To avoid it , what you should do is
using fetchrow() to get the value of the line by id
foreach user_name and user_postee check if the value of them matching the array value your fetched , if nothing changed or Null, then use the old value from array , if new value exist use new value insert into the array , finally use update to update the new array into database
Assume your Table Column is also "user_name" and "user_postee"
public function updateUserRest($id, $nom,$poste)
{
$row = $this->fetchRow('user_id = '. (int)$id);
if(!empty($nom) && $row['user_name'] != trim($nom)){
$row['user_name'] = $nom;
}
if(!empty($poste) && $row['user_poste'] != trim($poste)){
$row['user_poste'] = $poste;
}
$result=$this->update($row, 'user_id = '. (int)$id);
return $result;
}
I'm working on this project that have foreign keys on two tables. By using a form I'm trying to insert a new record to the database. And there's also an image path in the db and I'm inserting the image path via the form. I'm using codeigniter file upload library. Other fields of the database table get updated when i submit the form even the foreign key field. But the image path is not updating. When I submit the form it shows this error.
A Database Error Occurred
Error Number: 1452
Cannot add or update a child row: a foreign key constraint fails (`bfh`.`products`, CONSTRAINT `category_fk` FOREIGN KEY (`category_id`) REFERENCES `categories` (`id`))
INSERT INTO `products` (`img`) VALUES ('assets/img//sakya.PNG')
Filename: C:/xampp/htdocs/CI-skeleton/system/database/DB_driver.php
Line Number: 691
Controller
public function add_product()
{
$result = 0;
$cat_id = $this->input->post("category_id");
$type_id = $this->input->post("type_id");
$pname = $this->input->post("p_name");
$images = $this->input->post("images");
$images = $_FILES['images']['name'];
$price = $this->input->post("price");
$this->load->model("Products_Model");
$product_id = $this->Products_Model->add_product( $cat_id, $type_id, $pname, $price);
if ($product_id != 0) {
$result = $this->Products_Model->add_product_images($images);
}
if ($result && $_FILES['images']['name'][0] != "") {
$this->load->model('Image_Upload');
$result = $this->Image_Upload->upload("assets/img");
}
$this->session->set_flashdata('result', $result);
redirect('Products');
}
Model
public function add_product( $cat_id, $type_id, $pname, $price)
{
$result = $this->db->get_where("products", array('name' => $pname));
if ($result->num_rows() != 0) {
return 0; // record already exists
} else {
$data = array(
'category_id' => $cat_id,
'type_id' => $type_id,
'name' => $pname,
'price' => $price
);
if( !$this->db->insert('products', $data)) {
return -1; // error
}else{
return $this->db->insert_id();
}
return 1; // success
}
}
public function add_product_images($images)
{
$path = "assets/img/";
foreach ($images as $image) {
// if no images were given for the item
if ($image == "") {
return 1;
}
$data = array(
'img' => $path."/".$image
);
if ( ! $this->db->insert('products', $data)) {
return 0; // if something goes wrong
}
}
return 1;
}
You should use "update" query on the behalf of insert in add_product_images().
Because "insert" will add a new record of the product and there is no any category id(Foreign Key) with this that's why shows this error.
So try to update image.
you have two variables with the same name and thats the problem.
You need have different variable name.
I hope this will help you.
there are some problems in this script
if model you wrote, function add product. if your query failed, returns -1 otherwise return product Id
but if product was in database it returns 0, then in controller: you check if product_id != 0 then insert images. so you don't care if product didn't exists in database, you failed you insert that in table or not
in add_product_images you check if ($image == "") . I don't understand how you get that image array ($images) is empty if this statement is true. you can check if (sizeof($images) == 0) before foreach to check emptiness of image array ($images)
I just want to import csv file data to the database table. All fields were inserted successfully except my custom field that is date field(added_date).
It is display the error that.
Error: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'added_date' cannot be null
And below is my code for insertion csv data.
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
{
$rs[$cnt]['client_id'] = $emapData[0];
$rs[$cnt]['name'] = $emapData[1];
$rs[$cnt]['address1'] = $emapData[3];
$rs[$cnt]['address2'] = $emapData[4];
$rs[$cnt]['county'] = $emapData[8];
$rs[$cnt]['city'] = $emapData[6];
$rs[$cnt]['country'] = $emapData[8];
$rs[$cnt]['postcode'] = $emapData[7];
$rs[$cnt]['email_label'] = $emapData[14];
$rs[$cnt]['time_spent_on_site'] = $emapData[20];
$rs[$cnt]['added_date'] = date('Y-m-d H:i:s'); <== gives error that integrity constrains violation.
$cnt++;
}
fclose($file);
if (count($rs) > 0)
{
$customers = TableRegistry::get('Customers');
$entities = $customers->newEntities($rs);
$customers->connection()->transactional(function () use ($customers, $entities) {
foreach ($entities as $entity)
{
$customers->save($entity);
}
});
}
And database table structure is as follows:
Thanks you so much.
Its concept introduce in Cakephp 3.x that we need to use
$rs[$cnt]['added_date'] = new \DateTime('now');
in place of
$rs[$cnt]['added_date'] = date('Y-m-d H:i:s'); //Deprecated in Cakephp 3.x
Thank you so much for your approach.
i have a trouble when retrieve last insert id in codeigniter.
when i try to debug like var_dump();
the output just send int(0)
i use uuid as id with primary key. this is the code:
$this->db->set('id_customer','uuid_short()',FALSE);
$query = $this->db->insert('customer',$data);
$id = $this->db->insert_id();
echo var_dump($id);
if($query)
{
$array = array(
'kode_trans' => 'uuid()',
'trans_date' => 'NOW()'
);
$this->db->set('id_customer','$id');
$this->db->set($array,'',FALSE);
$this->db->insert('transaction_header');
return $id;
}else{
return FALSE;
}
im newbie in ci.
there is something wrong with my code?
The "insert_id" function uses PHP's mysql_insert_id function, which returns "The ID generated for an AUTO_INCREMENT column by the previous query on success, 0 if the previous query does not generate an AUTO_INCREMENT value"
You could try it this way;
$id = uuid_short();
$data['id_customer'] = $id;
$query = $this->db->insert('customer', $data);
if ( $query )
{
$array = array(
'kode_trans' => 'uuid()',
'trans_date' => 'NOW()'
);
$query = $this->db->insert('transaction_header', $array);
return $id;
}
else
{
return false;
}