【问题标题】:Laravel Morph Many from two columnsLaravel Morph 许多来自两列
【发布时间】:2020-09-11 13:22:09
【问题描述】:

我需要找到一种方法来修改 morphMany 关系以变形两个不同的列。这是正在变形的表创建语法:

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;

发件人和收件人都可以是用户。因此,我想根据两者中包含 user_id 的任何列进行变形。

这仅查看发件人是否是用户,而不是收件人。

return $this->morphMany(Friendship::class, 'sender');

查询的输出是:

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"

我们真正想要的是:

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")

我该如何做到这一点?

【问题讨论】:

标签: php mysql laravel polymorphism


【解决方案1】:

https://github.com/staudenmeir/laravel-merged-relations

这个作曲家包能够解决它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-18
    • 1970-01-01
    • 2019-08-15
    • 2016-11-25
    • 2021-10-08
    • 2021-09-05
    • 1970-01-01
    • 2022-01-22
    相关资源
    最近更新 更多