Q
Q
QR2016-07-12 13:01:43
MySQL
QR, 2016-07-12 13:01:43

How to maintain data integrity in the database without triggers?

How to maintain data integrity in the database without triggers?
Suppose we have invoices that are issued to different customers and services that are provided to different customers. I would like to prohibit billing at the index level for those services that were not provided to this company.
Base scheme:

CREATE TABLE `customers` (
  `id` INT(10) NOT NULL,
  `name` varchar(20) NOT NULL,
  PRIMARY KEY (`id`)
);

CREATE TABLE `bills` (
  `id` INT(10) NOT NULL,
  `number` varchar(6) NOT NULL,
  `customer` INT(10) NOT NULL,
  `creation_date` DATE NOT NULL,
  PRIMARY KEY (`id`)
);

CREATE TABLE `services` (
  `id` INT(10) NOT NULL,
  `service_name` varchar(50) NOT NULL,
  `customer` INT(10) NOT NULL,
  PRIMARY KEY (`id`)
);

CREATE TABLE `Untitled` (
  `id` INT NOT NULL,
  `bill` INT NOT NULL,
  `service` INT NOT NULL,
  PRIMARY KEY (`id`)
);

ALTER TABLE `bills` ADD CONSTRAINT `bills_fk0` FOREIGN KEY (`customer`) REFERENCES `customers`(`id`);

ALTER TABLE `services` ADD CONSTRAINT `services_fk0` FOREIGN KEY (`customer`) REFERENCES `customers`(`id`);

ALTER TABLE `Untitled` ADD CONSTRAINT `Untitled_fk0` FOREIGN KEY (`bill`) REFERENCES `bills`(`id`);

ALTER TABLE `Untitled` ADD CONSTRAINT `Untitled_fk1` FOREIGN KEY (`service`) REFERENCES `services`(`id`);

That is, how to disable the ability to insert data about services rendered for other companies in the `bills` table?
Thanks in advance.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey, 2016-07-12
@TheRuby

The client orders transportation, for example, through the website, it is checked in the programming language that at least one service is selected and then an invoice is created and the order is linked to the invoice.

START TRANSACTION;
INSERT INTO `bills`(`custom_id`) VALUES ($ид_клиента);

$bill_id = mysqli_last_inserted_id
And add what services you need to provide. Check whether it is done or not, do it yourself.
foreach ($массив с ИД зказанных услуг) {
INSERT INTO `order_service`(`bill_id`,`service_id`) VALUES ($bill_id,$service_id);
};
COMMIT;

That is, we get 1 account for 1 client, and for the life of you, you won’t be able to add 1 more client to the account. All services will be tied to this account.
After completion, we collect all the completed ordered services and expose to the client:
SELECT `service_id` 
FROM `order_service`  
WHERE `bill_id`=$по счету

Finish names and other things with joins.

D
Dmitry Kovalsky, 2016-07-12
@dmitryKovalskiy

Do you consider the option to write a stored procedure with a data addition transaction with the necessary checks?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question