I have carefully followed the documentation and set up 2 models, Author and Book. The relationship between them is such that Author has many Books and Book belongs to an Author. However, despite having the author_id field in the books table, the association appears to be empty. When inspecting the object structure using the Vue Browser add-on, the following data is seen:
$connection:"entities"
$name:"authors"
data:Object
21bc3055-ce90-4119-a68b-9bf2734b596b:Object
$id:"21bc3055-ce90-4119-a68b-9bf2734b596b"
name:"John Doe"
...
books:Array[0]
As for the books section:
$connection:"entities"
$name:"books"
data:Object
0537de72-2381-43b3-9132-831701272054:Object
$id:"0537de72-2381-43b3-9132-831701272054"
title:"Some Book"
...
author_id:"21bc3055-ce90-4119-a68b-9bf2734b596b"
The Author Model looks like this:
import { Model } from '@vuex-orm/core'
import Book from './book'
class Author extends Model {
static entity = 'authors'
static fields () {
return {
id: this.attr(null),
title: this.attr(null)
...,
books: this.hasMany(Book, 'author_id')
}
}
}
export default Author;
And here's the Book Model:
import { Model } from '@vuex-orm/core'
import Author from './author'
class Book extends Model {
static entity = 'books'
static fields () {
return {
id: this.attr(null),
name: this.attr(null),
...,
author_id: this.attr(null),
author: this.belongsTo(Author, 'author_id')
}
}
}
export default Book;
This is my code in store/index.js:
import Vue from 'vue'
import Vuex from 'vuex'
import VuexORM from "@vuex-orm/core";
import Author from "./models/author";
import Book from "./models/book";
import * as auth from '../store/modules/auth.js'
import * as authors from './modules/author.js'
import * as books from '../store/modules/books.js'
Vue.use(Vuex);
const database = new VuexORM.Database();
database.register(Author);
database.register(Book);
export default new Vuex.Store({
plugins: [VuexORM.install(database)],
modules: {
auth,
authors,
books,
},
state: {
},
mutations: {
},
actions: {
},
getters: {
}
})
Please note that even though the association seems intact on the backend, when it is inserted into VuexORM, the association does not get saved. In the mutation function of the store, I have tried to manually set the association but it still doesn't work as expected.
If you check the console log after insertion, the book.author field appears as null. How can I ensure that the author association is properly saved?