Невозможно получить доступ к данным связанных сущностей в Vuex ORM соединения / сводная таблица - PullRequest
0 голосов
/ 26 апреля 2020

Я установил сводную таблицу для задач / категорий, которая называется TaskCategory. Когда я получаю к нему доступ через Задачи, я не могу получить доступ к категориям, даже если установлены отношения.

Шаги для воспроизведения проблемы

Определение моделей [...]

Task. js

import {Model} from '@vuex-orm/core'
import TaskCategory from "@/models/TaskCategory";

export default class Task extends Model {
    // This is the name used as module name of the Vuex Store.
    static entity = 'tasks';

    // List of all fields (schema) of the post model. `this.attr` is used
    // for the generic field type. The argument is the default value.
    static fields() {
        return {
            id: this.uid(),
            title: this.attr(''),
            categories: this.hasMany(TaskCategory, 'task_id'),
        }
    }
}

Категория. js

import {Model} from '@vuex-orm/core'
import TaskCategory from "@/models/TaskCategory";

export default class Category extends Model {
    // This is the name used as module name of the Vuex Store.
    static entity = 'categories';

    // List of all fields (schema) of the post model. `this.attr` is used
    // for the generic field type. The argument is the default value.
    static fields() {
        return {
            id: this.uid(),
            title: this.attr(''),
            tasks: this.hasMany(TaskCategory, 'category_id'),
        }
    }
}

TaskCategory. js

import {Model} from "@vuex-orm/core";
import Category from "@/models/Category";
import Task from "@/models/Task";

export default class TaskCategory extends Model {
    static entity = 'taskCategory';

    static primaryKey = ['task_id', 'category_id'];

    static fields() {
        return {
            id: this.uid(),
            task_id: this.attr(null),
            task: this.belongsTo(Task, 'task_id'),
            category_id: this.attr(null),
            category: this.belongsTo(Category, 'category_id'),
            order: this.attr(null)
        }
    }
}

Создать данные [... ]

Создание категорий

Category.insert({
    data: [
        {
            title: 'urgent'
        },
        {
            title: 'important'
        }
    ]
});

Создание задач и назначение объединений

Task.create({
            data: [
                {
                    title: 'This'
                },
                {
                    title: 'that'
                },
                {
                    title: 'the'
                },
                {
                    title: 'other.'
                },
            ]
        }).then((c) => {

            const target_categories = Category.query()
                .where('title', 'urgent')
                .orWhere('title', 'important')
                .get();

            c.tasks.forEach((t) => {
                target_categories.forEach((tc) => {
                    Task.insertOrUpdate({
                        data: {
                            id: t.id,
                            categories: [
                                {
                                    task_id: t.id,
                                    category_id: tc.id,
                                    order: Math.round(Math.random() * (5 - 1) + 1)
                                }
                            ]
                        }
                    })
                })
            })
        })

Извлечение данных [...]

Task.query().withAll().get();

Ouput

[
  {
    "$id": "$uid4",
    "id": "$uid4",
    "title": "This",
    "categories": [
      {
        "$id": "[\"$uid4\",\"$uid2\"]",
        "id": "$uid8",
        "task_id": "$uid4",
        "task": null,
        "category_id": "$uid2",
        "category": null,
        "order": 3
      },
      {
        "$id": "[\"$uid4\",\"$uid3\"]",
        "id": "$uid9",
        "task_id": "$uid4",
        "task": null,
        "category_id": "$uid3",
        "category": null,
        "order": 4
      }
    ]
  },
  {
    "$id": "$uid5",
    "id": "$uid5",
    "title": "that",
    "categories": [
      {
        "$id": "[\"$uid5\",\"$uid2\"]",
        "id": "$uid10",
        "task_id": "$uid5",
        "task": null,
        "category_id": "$uid2",
        "category": null,
        "order": 2
      },
      {
        "$id": "[\"$uid5\",\"$uid3\"]",
        "id": "$uid11",
        "task_id": "$uid5",
        "task": null,
        "category_id": "$uid3",
        "category": null,
        "order": 4
      }
    ]
  },
  {
    "$id": "$uid6",
    "id": "$uid6",
    "title": "the",
    "categories": [
      {
        "$id": "[\"$uid6\",\"$uid2\"]",
        "id": "$uid12",
        "task_id": "$uid6",
        "task": null,
        "category_id": "$uid2",
        "category": null,
        "order": 2
      },
      {
        "$id": "[\"$uid6\",\"$uid3\"]",
        "id": "$uid13",
        "task_id": "$uid6",
        "task": null,
        "category_id": "$uid3",
        "category": null,
        "order": 2
      }
    ]
  },
  {
    "$id": "$uid7",
    "id": "$uid7",
    "title": "other.",
    "categories": [
      {
        "$id": "[\"$uid7\",\"$uid2\"]",
        "id": "$uid14",
        "task_id": "$uid7",
        "task": null,
        "category_id": "$uid2",
        "category": null,
        "order": 4
      },
      {
        "$id": "[\"$uid7\",\"$uid3\"]",
        "id": "$uid15",
        "task_id": "$uid7",
        "task": null,
        "category_id": "$uid3",
        "category": null,
        "order": 5
      }
    ]
  }
]

Ожидаемое поведение

Я должен иметь доступ к объединенной категории через TaskCategory, поскольку для нее настроена модель, используя соответствующий идентификатор

Версии

  • Vuex ORM: 0.36.3
  • Vue: 2.6.11
  • упаковка. json:
{
  "name": "todo-helper",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "test:unit": "vue-cli-service test:unit",
    "test:e2e": "vue-cli-service test:e2e",
    "lint": "vue-cli-service lint"
  },
  "dependencies": {
    "@fortawesome/fontawesome-svg-core": "^1.2.28",
    "@fortawesome/free-solid-svg-icons": "^5.13.0",
    "@fortawesome/vue-fontawesome": "^0.1.9",
    "@vuex-orm/core": "^0.36.3",
    "core-js": "^3.6.4",
    "vue": "^2.6.11",
    "vue-router": "^3.1.6",
    "vuex": "^3.1.3"
  },
  "devDependencies": {
    "@vue/cli-plugin-babel": "~4.3.0",
    "@vue/cli-plugin-e2e-cypress": "~4.3.0",
    "@vue/cli-plugin-eslint": "~4.3.0",
    "@vue/cli-plugin-unit-jest": "~4.3.0",
    "@vue/cli-plugin-vuex": "~4.3.0",
    "@vue/cli-service": "~4.3.0",
    "@vue/test-utils": "1.0.0-beta.31",
    "babel-eslint": "^10.1.0",
    "eslint": "^6.7.2",
    "eslint-plugin-vue": "^6.2.2",
    "sass": "^1.26.3",
    "sass-loader": "^8.0.2",
    "vue-cli-plugin-bootstrap": "~1.0.0-alpha.0",
    "vue-template-compiler": "^2.6.11"
  },
  "eslintConfig": {
    "root": true,
    "env": {
      "node": true
    },
    "extends": [
      "plugin:vue/essential",
      "eslint:recommended"
    ],
    "parserOptions": {
      "parser": "babel-eslint"
    },
    "rules": {},
    "overrides": [
      {
        "files": [
          "**/__tests__/*.{j,t}s?(x)",
          "**/tests/unit/**/*.spec.{j,t}s?(x)"
        ],
        "env": {
          "jest": true
        }
      }
    ]
  },
  "browserslist": [
    "> 1%",
    "last 2 versions",
    "not dead"
  ],
  "jest": {
    "preset": "@vue/cli-plugin-unit-jest"
  }
}

I ' Мы также подняли вопрос здесь

1 Ответ

0 голосов
/ 26 апреля 2020

Как указано по вопросу здесь Я должен был использовать:

Task.query().withAllRecursive(2).get();

Где 2 - глубина, с которой можно перейти к категориям на другой стороне TaskCategory присоединиться

...