Laravel Morph Many from two columns - php

I need to find a way to modify the morphMany relationship to morph two different columns. Here is the table create syntax that is being morphed:
CREATE TABLE `user_friendships` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`sender_type` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`sender_id` bigint(20) unsigned NOT NULL,
`recipient_type` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`recipient_id` bigint(20) unsigned NOT NULL,
`status` tinyint(4) NOT NULL DEFAULT '0',
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `user_friendships_sender_type_sender_id_index` (`sender_type`,`sender_id`),
KEY `user_friendships_recipient_type_recipient_id_index` (`recipient_type`,`recipient_id`)
) ENGINE=InnoDB AUTO_INCREMENT=12332 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
Sender and recipient can both be a user. So I want to morph based on whatever column of the two contains the user_id.
This only looks at if the sender is the user, but not the recipient.
return $this->morphMany(Friendship::class, 'sender');
The output of the query from that is:
select * from `user_friendships` where `user_friendships`.`sender_id` = 5971 and `user_friendships`.`sender_id` is not null and `user_friendships`.`sender_type` = "App\\\User"
What we actually want is:
select * from `user_friendships` where (`user_friendships`.`sender_id` = 5971 and `user_friendships`.`sender_id` is not null and `user_friendships`.`sender_type` = "App\\\User") OR (`user_friendships`.`recipient_id` = 5971 and `user_friendships`.`recipient_id` is not null and `user_friendships`.`recipient_type` = "App\\\User")
How do I accomplish this?

https://github.com/staudenmeir/laravel-merged-relations
This composer package was able to solve it.

Related

How to use is_unique form validation within a specific range of record?

I have a table called participants:
CREATE TABLE IF NOT EXISTS `participants` (
`id` int(8) NOT NULL AUTO_INCREMENT,
`email` varchar(30) NOT NULL,
`name` varchar(40) NOT NULL,
`birthdate` date NOT NULL,
`personal_number` varchar(16) DEFAULT NULL,
`phone` varchar(16) NOT NULL,
`photo` varchar(100) NOT NULL,
`address` text NOT NULL,
`city_id` int(3) DEFAULT NULL,
`tournament_id` int(8) NOT NULL,
`time_created` datetime NOT NULL,
`time_modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `city_id` (`city_id`),
KEY `tournament_id` (`tournament_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
The rule for creating participants is each registered email address can only participate in one tournament (foreign key tournament_id); therefore two records with the same email address but different tournament_id should be allowed.
Is is_unique form validation able to do this operation? Or should I create a callback or a helper?
is_unique is just a short name for value_does_not_already_exists_in_a_single_column.
So, no - it won't do the job; you'll need a callback.

mysql unique for multiple columns

When payment happen, sometimes its captured double entry in table.
I want to ignore double entry capture so i want to insert records when these created, user_id, amount fields should be unique.
How do i make it ? Below is my table.
CREATE TABLE `transactions` (
`id` int(20) NOT NULL AUTO_INCREMENT,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
`user_id` int(20) NOT NULL,
`project_id` int(20) DEFAULT NULL,
`foreign_id` int(20) NOT NULL,
`class` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
`transaction_type_id` int(20) DEFAULT NULL,
`amount` float(10,2) NOT NULL,
`description` text COLLATE utf8_unicode_ci,
`payment_gateway_id` int(20) DEFAULT NULL,
`gateway_fees` float(10,2) NOT NULL,
`is_old` tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=266 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
To strictly answer your question, you create a unique composite key on the combination of those 3 columns. That way no two rows can exist with a combination of the 3 of them in the composite index.
CREATE TABLE `transactions2` (
`id` int(20) NOT NULL AUTO_INCREMENT,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
`user_id` int(20) NOT NULL,
`project_id` int(20) DEFAULT NULL,
`foreign_id` int(20) NOT NULL,
`class` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
`transaction_type_id` int(20) DEFAULT NULL,
`amount` float(10,2) NOT NULL,
`description` text COLLATE utf8_unicode_ci,
`payment_gateway_id` int(20) DEFAULT NULL,
`gateway_fees` float(10,2) NOT NULL,
`is_old` tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
unique key(created,user_id,amount) -- <------------------- right here
);
insert some data to test it:
insert transactions2 (created,modified,user_id,project_id,foreign_id,class,
transaction_type_id,amount,description,payment_gateway_id,gateway_fees,is_old) values
('2009-01-01 12:00:00','2009-01-01 12:00:00',666,1,1,'a',1,100,'desc',1,12,1);
-- inserts fine (above)
Try it again with exactly the same data:
insert transactions2 (created,modified,user_id,project_id,foreign_id,class,
transaction_type_id,amount,description,payment_gateway_id,gateway_fees,is_old) values
('2009-01-01 12:00:00','2009-01-01 12:00:00',666,1,1,'a',1,100,'desc',1,12,1);
-- error 1062: Duplicate entry
-- change it barely:
insert transactions2 (created,modified,user_id,project_id,foreign_id,class,
transaction_type_id,amount,description,payment_gateway_id,gateway_fees,is_old) values
('2009-01-01 13:00:00','2009-01-01 12:00:00',666,1,1,'a',1,100,'desc',1,12,1);
-- inserts fine
Also, use ENGINE=INNODB. Read about that Here.
Please read Mysql multi column indexes a.k.a. composite indexes.
Lastly, the concept of what you are talking about is not far off from Insert on Duplicate Key Update. Just throwing that reference out there for you.
You can achieve the same using ,handling at the time of inserting,
You can try WHERE NOT EXISTS with INSERT.
Something like this.(You need to specify column name who has NOT NULL constraint,i missed all those columns)
INSERT INTO table_name(`created`,`user_id`,`amount`) VALUES =
'$created','$user_id','$amount'
WHERE NOT EXISTS
(SELECT *
FROM table_name
WHERE created ='$created' AND user_id='$user_id' AND amount='$amount')
Hope this helps.

#1215 - Cannot add foreign key constraint

I'm working a project with Yiiframwork and I have this table in my data base project
CREATE TABLE IF NOT EXISTS `tbl_annonce` (
`id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
`idEntreprise` tinyint(3) unsigned NOT NULL
COMMENT 'CONSTRAINT FOREIGN KEY (idEntreprise) REFERENCES tbl_entreprise(id)',
`titre` varchar(100) NOT NULL,
`detailleDiscription` varchar(5000) NOT NULL,
`categorie` varchar(100) DEFAULT NULL,
`typePoste` varchar(100) NOT NULL,
`salaireMin` varchar(80) NOT NULL,
`salaireMax` varchar(80) NOT NULL,
`niveauEtude` varchar(80) NOT NULL,
`niveauExperience` varchar(80) NOT NULL,
`langue` varchar(50) DEFAULT NULL,
`poste` varchar(50) NOT NULL,
`pays` varchar(50) NOT NULL,
`ville` varchar(50) NOT NULL,
`adresse` varchar(80) NOT NULL,
`datePublication` timestamp NOT NULL
DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`etat` varchar(50) NOT NULL,
`photo` varchar(255) NULL,
`nometr` text NOT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `fk_idEntrepriseAnn`
FOREIGN KEY (idEntreprise)
REFERENCES tbl_entreprise(id)
ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;
I only use 'comment' because I found it in a tutorial for a yii framework project.
I have got the attribute 'idEntreprise' as FK in my DB but when I entred other 'idEntreprise' that does note exist in my table entreprise it was not problem, instead it must be a problem.
So I added 'identreprise' as Fk and that have this problem now.
Hope you understand my problem :/
can any one helep me plz !!
To define a foreign key on a column, it must fulfil some conditions.
Child and parent column must have same column definition by type,
signed.
Parent column must have an index defined on it.
Make sure that
The column tbl_entreprise.id is indexed.
The column definition idEntreprise tinyint(3) unsigned in tbl_annonce matches
with that of tbl_entreprise.id
Refer to: MySQL: Foregin Key Constaints

MySQL Stored Procedure [Copy table 1 -> table 2]

My knowledge of MySQL/ SQL apart from the simple CRUD operations is basic.
If I had to use a stored procedure to move certain attributes (not in a specific order) to another table how could it be done?
These are the following tables. I want to move from the 1st to the 2nd table.
As you can see the datatype sizes are different for certain columns.
CREATE TABLE IF NOT EXISTS `source_cdr` (
`callstart` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`src` varchar(80) NOT NULL DEFAULT '',
`dst` varchar(80) NOT NULL DEFAULT '',
`accountcode` varchar(50) NOT NULL,
`uniqueid` varchar(100) NOT NULL,
`ID` int(11) NOT NULL AUTO_INCREMENT,
`callanswer` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`callend` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`disposition` varchar(50) NOT NULL,
`cdr_id` int(11) unsigned NOT NULL DEFAULT '0',
`pin_code` varchar(4) NOT NULL,
`provider` int(11) NOT NULL,
PRIMARY KEY (`ID`),
KEY `calldate_idx` (`callstart`) USING BTREE,
KEY `idx_acc_code_calldate` (`accountcode`,`callstart`) USING BTREE,
KEY `uniqueid` (`uniqueid`),
KEY `cdr_id` (`cdr_id`),
KEY `idx_uniqueid_cdr_id` (`uniqueid`,`cdr_id`)
) ENGINE=MyISAM;
--
CREATE TABLE IF NOT EXISTS `destination_cdr` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`calldate` datetime NOT NULL,
`source` varchar(80) NOT NULL,
`destination` varchar(80) NOT NULL,
`account_code` varchar(30) DEFAULT NULL,
`pincode` varchar(45) NOT NULL,
`duration_call` bigint(20) NOT NULL DEFAULT '0',
`duration_talk` bigint(20) NOT NULL,
`disposition` varchar(255) NOT NULL,
`clid` varchar(80) DEFAULT NULL,
`cdr_id` bigint(20) DEFAULT NULL,
`vxcdr_id` bigint(20) DEFAULT NULL,
`provider` int(11) NOT NULL DEFAULT '0'
PRIMARY KEY (`id`)
) ENGINE=MyISAM;
EDIT 1
An example of a row
('2012-03-18 20:54:49', '5796', '0761100866', '103f0124ad510516f33cab132c0a695b', 'call-F1884808-6753-2F10-181C-3A#10.217.164.33', 308006367, '2012-03-18 20:55:05', '2012-03-18 20:55:51', '200 OK', 2, '', 0),
Thanks
You can use MySQL: INSERT ... SELECT Syntax to copy data from one table to the other.
Decide common fields in both and copy the same.
Example:
INSERT INTO TABLE2( COL1, COLx, ... ) SELECT colM, colY FROM TABLE1;
If the column sizes mismatch, data truncation takes place, and you can't overcome that but redefine the destination table columns.

Confusing mysql problem

I have got a problem with two tables:
CREATE TABLE IF NOT EXISTS `addresses` (
`adr_id` int(11) NOT NULL auto_increment,
`per_id` int(11) NOT NULL,
`adr_street` varchar(50) NOT NULL,
`adr_houseno` int(11) default NULL,
`adr_housenoadd` varchar(10) default NULL,
`adr_postalcode` varchar(25) NOT NULL,
`adr_city` varchar(20) NOT NULL,
`adr_type` varchar(45) default NULL,
`cnt_id` int(11) NOT NULL,
`adr_date` date default NULL,
`sys-mut-dt` timestamp NULL default NULL,
`sys-mut-user` varchar(20) default NULL,
`sys-mut-id` int(11) NOT NULL default '0',
PRIMARY KEY (`adr_id`),
KEY `per_id` (`per_id`),
KEY `cnt_id` (`cnt_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;
--
-- RELATIES VOOR TABEL `addresses`:
-- `cnt_id`
-- `countries` -> `cnt_id`
-- `per_id`
-- `persons` -> `per_id`
--
CREATE TABLE `events` (
`evt_id` int(11) NOT NULL auto_increment,
`evt_name` varchar(50) NOT NULL,
`evt_description` varchar(100) default NULL,
`evt_startdate` date NOT NULL,
`evt_enddate` date default NULL,
`evt_starttime` time default NULL,
`evt_endtime` time default NULL,
`evt_amtpersons` int(11) default NULL,
`sts_id` int(11) NOT NULL,
`adr_id` int(11) default NULL,
`evt_amtPersonsSubs` tinyint(4) NOT NULL default '0',
`evt_photo` varchar(50) default NULL,
`sys-mut-dt` timestamp NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
`sys-mut-user` varchar(20) default NULL,
`sys-mut-id` int(11) NOT NULL default '0',
PRIMARY KEY (`evt_id`),
KEY `sts_id` (`sts_id`),
KEY `adr_id` (`adr_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
The problem is, when i try to delete a record from address table I get the following error
DELETE
FROM addresses
WHERE per_id = 45
1451 - Cannot delete or update a parent row: a foreign key constraint fails (`site/events`, CONSTRAINT `adr_id` FOREIGN KEY (`adr_id`) REFERENCES `addresses` (`adr_id`) ON DELETE NO ACTION ON UPDATE NO ACTION) ;
The weird thing is that there is no record with the same per_id or adr_id in the events table.
So what's going on over here?
How Can I solve this? ;-)
/* I think it means "How can I solve this?" */
It may sound stupid, but are you absolutely sure there are no child rows?
Could you please run this:
SELECT e.*
FROM addresses a
JOIN events e
ON e.adr_id = a.adr_id
WHERE a.per_id = 45

Categories