首页 > 解决方案 > Laravel - 是否可以通过数组元素作为表格中的文本在模型(belongsTo)之间建立关系

问题描述

我是 Laravel 的绝对初学者。

是否有可能通过数组元素在模型之间建立关系,比如 belongsTo。

table1 中的列如下所示:

mapping: ["misc","rates","photos"]

我需要类似于以下内容:

public function dependencies() : BelongsTo
{
    // This is impossible because "mapping" is array in Depends model and text type in database.
    return $this->belongsTo(Depends::class, 'mapping', 'element_of_array'); 
}

或类似的东西(hasMany 等)。

表如下所示:

CREATE TABLE `dependings` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`media_id` int(10) unsigned NOT NULL,
`type` varchar(30) COLLATE utf8mb4_unicode_ci NOT NULL,
`mapping` text COLLATE utf8mb4_unicode_ci NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `dependent_collection_mappings_collection_id_type_unique` (`media_id`,`type`),
CONSTRAINT `dependent_collection_mappings_collection_id_foreign` FOREIGN KEY (`media_id`) REFERENCES `media` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

标签: laraveleloquent

解决方案


推荐阅读