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();
Related
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.
I am inserting data into a database fine with the user entering a reference number eg 1234. Can I change my insert to not require the user to input the value and for the last value entered to be checked and then the reference number being inserted be incremented by one and then inserted with the other data. Bit of a new bee. Here is my current code
$Reference_No = $_POST['Reference_No'];
$Property_Name = $_POST['Property_Name'];
$Property_Area = $_POST['Property_Area'];
mysql_query("INSERT INTO properties (Reference_No, Property_Name, Property_Area)
VALUES ('$Reference_No', '$Property_Name', '$Property_Area')");
You need to make the Reference_No an AUTO_INCREMENT.
Step 1:Create table
CREATE TABLE properties (
Reference_No int AUTO_INCREMENT ,
Property_Name varchar(255),
Property_Area varchar(255),
PRIMARY_KEY (Reference_No)
)
Step 2 : Set the start for auto increment of primary key if you like
ALTER TABLE properties AUTO_INCREMENT=1234;
Step 3: Insert the data into the table
INSERT INTO properties (Property_Name, Property_Area)
VALUES ('$Property_Name', '$Property_Area')");
interogate the database for the Reference NO (where property name matches if you need it)
$reference_no_query = mysql_query("SELECT Reference_No FROM properties WHERE Property_Name = $Property_Name");
pull the Reference No out of the database
$Reference_no = mysql_fetch_array($reference_no_query)
display the Reference no
echo $Reference_no('Reference_no');
you can (and should) tie the data to a variable then echo the var like this:
$Reference_no_display = $Reference_no('Reference_no');
then display it directly from the variable anywere and as many times as you want in the page below the query:
echo $Reference_no_display;
This seems to do the trick for the final bit
printf("Last inserted record has id %d\n", mysql_insert_id());
I am trying to do an INSERT only if the combination of two columns (a and b) does not exist already. Otherwise, I want to do an UPDATE. The issue of the following code is that it always INSERTs a new row instead of updating when I want to. The reason I think, is because I don't manage do have a kind of two-unique-column in the settings of my table.
Does any one have a solution? Google doesn't seem to be my friend today..
The table:
id : int, primary, AI
a b c and d : int
The code:
$req = $connexion -> prepare("
INSERT INTO position (a,b,c,d)
VALUES (:a,:b,:c,:d)
ON DUPLICATE KEY UPDATE
c=:c;");
$position->bindParam(':a', $a);
$position->bindParam(':b', $b);
$position->bindParam(':c', $c);
$position->bindParam(':d', $d);
$a = $val_a;
$b = $val_b;
$c = $val_c;
$d = $val_d;
$req -> execute();
ON DUPLICATE KEY requires a UNIQUE KEY if you are not matching to the PRIMARY KEY. You can add a UNIQUE KEY by using an ALTER TABLE query
ALTER TABLE position ADD UNIQUE KEY (a,b)
Have you already tried to alter the table to reflect what you need? try this before executing your code.
ALTER TABLE `position` ADD UNIQUE `unique_index`(`a`, `b`);
I would like to insert in relation table an other attribute ("tiers_temps" in my example) that ids, is it possible with the function "link()" or others ?
I use actually this codes, but I must update the filed "tiers_temps" :
$Examen->link('Users', $listAdd);
with the table "user_has_examen" structure :
Field Type Null Key Default Extra
user_id int(11) NO PRI 0
examen_id int(11) NO PRI 0
tiers_temps int(11) YES NULL
There is un error in your proposition. The object $user refers to the table "user" and not "user_has_examen" (not descibe before, that's right) so "tiers_temps" doesn't exist for user.
This solution works but I loop access Doctrine...
foreach($user as $userId){
$UserExam = Doctrine::getTable('UserExamen')->findByDql('user_id = ? AND examen_id = ?', array($userId, $exam))->getFirst();
if($UserExam->tiers_temps != $users[$userId]){
$UserExam->tiers_temps = $users[$userId];
$UserExam->save();
}
}
I didn't find a nice way to interact with an intermediate item. But you can act on the relations to retrieve all user, and then, apply your tiers_temps value before saving your Examen:
$Examen->link('Users', $listAdd);
$users = $Examen->Users;
foreach ($users as $user)
{
$user->tiers_temps = '45';
}
When I find myself in these situations I prefer to give up the table many to many Identifying and move to a structure like this:
id
user_id
examen_id
tiers_temps
because I find it very inconvenient to manage the value tiers_temps in the structure you used.
I have my database with table test1.
It has a primary id "Id" which is auto-increment.
Now the id is in the format 1,2,3.. . .Is it possible to store the primary Id as
PNR1,PNR2,PNR3 .. . . and so on(with auto-increment).
No. Either add the prefix in the query, or use a view instead.
Not really, but you can use another column (but a view)
this is already covered here:
MySQL Auto Increment Custom Values
Yes you can do it if you have INT prefix. You have id as INT in table
// START PREFIX
$query = mysql_query("SELECT id FROM `table_name` ORDER BY id DESC LIMIT 1");
// GET THE LAST ID MAKE SURE IN TABLE YOU 9991
while ($row = mysql_fetch_object($query)) {
$lastId = $row->id;
}
list($prefix,$Id) = explode('999',$lastId );
$Id = ($Id+1);
$new_id = '999'.$Id;
// END PREFIX
$insertQuery = mysql_query("INSERT INTO `table_name` SET id = '".$new_id."',...");
Hi, I made it work in this way :
Products Table (products):
id_prod(varchar(11), NOT NULL, PK), name(varchar(40))
Products Sequence Table (productidseq):
id(AI, PK, NOT NULL)
Before Insert Trigger in Products Table:
CREATE DEFINER=`root`#`localhost` TRIGGER `dbname`.`products_BEFORE_INSERT` BEFORE INSERT ON `products` FOR EACH ROW
BEGIN
insert into productidseq (id) values(NULL);
set new.id_prod = concat('PROD or any prefix here',last_insert_id());
set #productId = new.id_prod; -- To use outside of trigger this variable is useful.
END
When you run below query :
insert into products (name) values('Bat');
data inside tables will we be like this :
products:
id | name
---|-----
1 | Bat
productidseq:
id
---
1
If any better way than this or any cons with this, please comment below. Thanks.