eloquent orm select where and then update - php

I have some code
public function addvote($id,$varia){
$pollsres = Pollsres::where('poll_id', '=',$id)->where('poll_variant','=',$varia)->get();
// and poll_variant = ?',[$id,$varia])->get();
if($pollsres->isEmpty()){
$pollres = new Pollsres();
$pollres->poll_id = $id;
$pollres->poll_variant = $varia;
$pollres->poll_count = 1;
$pollres->save();
}else{
//return response()->json($pollsres);
var_dump($pollsres);
}
}
In db i have 1 record $id = 1 and $varia = 1 but have i can update $pollsres->poll_count i have error, if i update $pollsres[0]->poll_count i update all record not only why have where expression (testing whith 2 record in db)
i whant check if i have record in db whith where if not add new if have edit this record

Because your table does not have primary key.
You need adding auto increment primary key for you table, because Laravel/Lumen does not support composite primary key (i.e: 2 primary keys or more).
And then the problem will be solved.

Related

How do I can skip a duplicate value before adding it to the database?

I have table with favorites programm. I will add with ajax query to database favorite programm id's to table with user id. How I can skip a duplicate programm id with current user id.
I now create this method for skip duplicate values but not working in calling:
public function test($programm_id){
$fav = new \App\Favorite;
$user_id = Auth::id();
$fav_count = $fav::where('id_user', Auth::user()->id)->count();
$getFavorites = $fav::where('id_user', $user_id)->get()->toArray();
$userProgramms = $fav->where('id_user', $user_id)->select('id_program')->get()->toArray();
$bool = true;
foreach ($userProgramms as $array) {
foreach ($array as $value) {
if($value === $programm_id) $bool = false;
}
}
if($fav_count <= 5){
if ($bool){
$fav->id_user = Auth::user()->id;
$fav->id_program = $programm_id;
$fav->save();
}
}
}
Here my table:
Please see my method favorite() in this controller: Controller
My updated code can't more 1 saves to database.
$fav = new \App\Favorite;
$fav_count = $fav::where('id_user', Auth::user()->id)->count();
if($fav_count <= 5)
{
$fav->updateOrInsert(['id_user' => Auth::id()], ['id_program' => $post['id_program']]);
}
Every user can add to table max 6 favorite id programms
Add an unique index on the table:
ALTER TABLE `tableName` ADD UNIQUE `unique_index`(`id_user`, `id_program`);
and use the INSERT INTO ... OR UPDATE:
INSERT INTO t1 (a,b,c) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE c=c+1;
UPDATE t1 SET c=c+1 WHERE a=1;
In that manner your query will insert a new record if there isn't already a record with the same couple of id_user and id_program values, in case of it it'll perform an update on that row.
If you want to do it in PHP and assuming your values are stored in an array, you can use array_unique().
Check it out here: http://php.net/manual/en/function.array-unique.php

Eloquent insert id with sequence next value

I would like to create a new record in a PostgreSQL database table with Laravel eloquent but the table id is not auto incremented and it's make my life more difficult.
Here is the sample structure:
CREATE TABLE billing (
id int8,
companyname varchar(255) NOT NULL,
...
PRIMARY KEY (id),
);
The id field isn't auto incremented and I can't change this. Furthermore I can't write triggers.
In Laravel I would like to do something like this:
$billing = new Billing;
$billing->id = DB::raw("nextval('sequence')");
$billing->companyname = $request->companyname;
// ...
$billing->save();
It's working but it seems messy.
How could I simplify the DB (id) part of my code?
Thanks!
Try with
$billing->id = DB::getPdo()->lastInsertId(); // + 1 ?
with this
$nextval=DB::select(DB::raw("SELECT nextval('".(new Billing())->getTable()."_id_seq') as seq"))[0]->seq;
$billing = new Billing;
$billing->id = $nextval;
$billing->companyname = $request->companyname;
// ...
$billing->save();

ON DUPLICATE UPDATE not works with some row

I am using ON DUPLICATE UPDATE on my query, some of the result didn't store it. I tried all the possible way, but those still remain the same. here are the database picture.
Those NULL, is the row which didn't store successfully; the result should be 1 instead of NULL.
if($remark){
$query3 = "INSERT INTO `audit_section_remarkrecord` SET remark = '$remark', form_details_subquestion_id = '$form_details_subquestion_id', form_details_section_id = '$form_details_section_id', audit_section_no = '$audit_no' ON DUPLICATE KEY UPDATE
form_details_section_id = '$form_details_section_id' , remark = '$remark'";
$result3 = $db->query($query3);
$query4 = "UPDATE `remarkrecord_update_details` SET form_details_section_id = '$form_details_section_id', userlog = '$user_staff', ipaddress = '$ip' WHERE form_details_subquestion_id = '$form_details_subquestion_id' AND audit_section_no = '$audit_no' ";
$result4 = $db->query($query4);
}else{
}
}
Table Structure
Try changing one of your columns you are inserting value to primary key or add UNIQUE constraint to the column.
ALTER TABLE audit_section_remarkrecord ADD UNIQUE KEY (your column);
As there is currently only a unique key on the Primary Key, an auto-increment, you are going to have difficulty generating a unique key clash on an insert on duplicate key update (IODKU). Therefore, some other unique key needs to be created (even a composite), that will trigger the clash of a unique key and allow IODKU to work as expected.

How to insert unique table data except id in codeigniter?

How can insert the unique row in mysql?
id and userid both are different column.
I have set id is unique.But userid and checkin column should not be repeated.
Is this possible?
if($this->dx_auth->is_logged_in()){
$insertData['userid'] = $this->dx_auth->get_user_id();
$insertData['checkin'] = $checkin;
$insertData['checkout'] = $checkout;
$insertData['location'] = $location;
$insertData['guest'] = $nof_guest;
$id = $this->dx_auth->get_user_id();
$result = $this->Common_model->getTableData('searchlist', array("userid" => $id));
if($result->num_rows > 4){
$res = $result->result();
$del_id = $res[0]->id;
$conditions = array("id" => $del_id);
$this->Common_model->deleteTableData('searchlist', $conditions);
}
if($location != "0"){
$this->Common_model->inserTableData('searchlist', $insertData);}}
You can keep your id as primary key and auto increment for your user table.
Then, you have to create combined unique key for userid and checkin.
CREATE UNIQUE INDEX user_checkin_time ON searchlist (userid, checkin);
In controller, you have to validate the userid and checkin before insert / update.
$isExist = $this->Common_model->getTableData('searchlist', array("userid" => $id,"checkin"=>$checkin));
if($isExist->num_rows()>0)
{
// throw error message as checkin time already exist
}
else
{
// continue with further code
}
In this case, you can really make the userid and checkin columns as a composite primary key. If you want you can still use id as the primary key and create a unique index for the 2 other columns combined.
You should probably also check if the record exists before you insert a new combination that would result in a MySQL error.
Cheers!

How to INSERT new record using column field default with FK

I'm trying to INSERT a new record into a table (employee) where a few of the columns are FK's that are linked to other tables (license and car) PK's. The table(1) has a default set for these columns that reflect the same value listed in the table(2+3) PK.
Example:
INSERT INTO employee (Emp_ID, Lic_ID, Car_ID) Values ('1234', ' ', ' ')
Tables:
table(1) = employee
PK = Emp_ID
FK = Lic_ID, default = 1
FK = Car_ID, default = 1
table(2) = license
PK = Lic_ID
records = 1 through 8
table(3) = car
PK = Car_ID
records = 1 through 6
The problem is, whenever I try to run that insert statement, I get:
Error: 1452 "Cannot add or update a child row: a foreign key constraint fails"
I don't want to have to enter a value into the Lic_ID or Car_ID fields when I create the employee because they may not have either one of those assigned to them. What I want is for the table to use the default value of '1', what am I doing wrong?
If you want to use default values, then remove field names from the INSERT statement -
INSERT INTO employee (Emp_ID) Values ('1234');

Categories