When using the hasMany/belongsTo relationship in VuexORM, the result may sometimes be

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?

Answer №1

To begin, you must inform VuexORM to fetch the relationship by using:

Book.query().with("author").first()

For more information on relationships in VuexORM, check out their documentation here:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A guide on extracting input values and transmitting them as a JSON object to the backend in Vue 3

I am currently working on a questionnaire that displays questions and their answers using vuejs. The backend will be managed by django. My objective is to extract the question id and answer from the questionnaire, package it as a JSON object, and send it t ...

Utilizing jQuery to Calculate Tab Scores

Last week, my teacher and I collaborated on a fun game called rEAndom game (). The game is created using javascript, jQuery, and HTML5. One interesting feature of the game is that when you press the TAB key, a div displaying the score appears. You can chec ...

Adjusting the height of the Tinymce Editor in React Grid Layout after the initial initialization

I am facing a challenge with my React Component that displays a tinymce editor. The task is to dynamically adjust the height of the editor after it has been initialized. To achieve this, I am utilizing the "React Grid Layout" package for resizing the compo ...

Updating ngModel using the value retrieved from a service call

After experiencing dissatisfaction with Angular's form validation, I decided to develop my own solution. However, I have encountered a perplexing issue that has me at a loss. Here is how my setup looks: I employ a directive to create a new form. Th ...

Allow users to edit the textarea only to input values, not from

I am trying to achieve a specific functionality with two input fields and one textarea. Whenever I type something in the input fields, their values are automatically populated in the textarea using .val(). Currently, this feature is working as intended, b ...

Utilizing a backup system to store environment variables within a configuration file

Currently, I am utilizing my environment variables by directly referencing process.env.NODE_ENV throughout my application. While this method works, it is becoming challenging to manage and keep track of. Therefore, I would like to consolidate all these var ...

The correct conclusion is reached by the function when the console.log statement is placed above the function call

By moving the console.log above the function call, the correct conclusion is reached. I double-checked multiple times by toggling the console.log on and off. Running on node.js v16.4.2. The input data is accurate. I attempted to replicate the issue in a di ...

Implement the click event binding using classes in Angular 2

If I have the template below, how can I use TypeScript to bind a click event by class? My goal is to retrieve attributes of the clicked element. <ul> <li id="1" class="selectModal">First</li> <li id="2" class="selectModal">Seco ...

karma - Plugin not located

Attempting to run JS test cases using karma, but consistently receiving a plugin not found error. Oddly enough, the same configuration file works perfectly for one of my co-workers. Below are the logs: $ karma start karma.conf.js 04 10 2016 17:51:24.755 ...

I am experiencing difficulty in detecting variable changes within my $scope function

I'm encountering an issue where a variable isn't being updated in a $scope function when there's a state change event. Despite seeing the variable update in the event listener, it doesn't reflect in the function. The code snippet in qu ...

When using jQuery, the .change() function will only be triggered after the user clicks a button or

Looking for assistance with an unusual issue in my JavaScript/jQuery code. The jQuery .change() function on a simple text input element only triggers when I click somewhere on the page, open the Chrome console, or press a key on the keyboard. It doesn&apo ...

Creating a ROT13 cipher in JavaScript

In my JS function, I need to handle a variable called i. My goal is to encode this variable using ROT13 before proceeding with the function. The challenge lies in decoding the variable and integrating it into the script. I came across a JavaScript implem ...

Utilize jQuery to wrap text within <b> tags and separate them with <br> tags

Upon receiving output in html string format from services, I am presented with the following: "<html>↵<h1>↵Example : ↵<br>Explanation↵</h1>↵<hr>↵<b>key1 : ABCD <br>key2 : 2016-10-18-18-38-29<br> ...

The PHP counter conceals the comma upon loading and does not display it permanently

I'm currently working on a PHP counter and encountering an issue with the comma display. I have implemented Number Format in a PHP function to print counter digits with commas every 3 digits, but the comma doesn't remain visible after the page lo ...

Establish a connection between the Discord Bot and a different channel

I need help with my Discord bot that should redirect someone to a different channel when they mention certain trigger word(s). I feel like there might be a missing line or two of code that I need to add to make it work properly. bot.on("message", messag ...

What is the method to retrieve the string value from a JavaScript String object?

Is there a way to extend a method to the String prototype and manipulate the string value? I'm facing some difficulty in accessing the actual string value, as this, the current object context, seems to refer to the string object instead. String.pro ...

Declaration of expansion panel with additional sub-expansion panels

I'm trying to wrap my head around the concept of using the v-expansion-panels component. Do I need to declare the parent component as v-expansion-panels in order for it to contain child v-expansion-panel components, or is just using v-expansion-panel ...

Is it possible to protect assets aside from JavaScript in Nodewebkit?

After coming across a post about securing the source code in a node-webkit desktop application on Stack Overflow, I began contemplating ways to safeguard my font files. Would using a snapshot approach, similar to the one mentioned in the post, be a viable ...

Getting PHP Post data into a jQuery ajax request can be achieved by using the `$_POST

I'm struggling to figure out how to pass the blog title into the data field of my ajax call. I've been searching for beginner tutorials on SQL, PHP, and AJAX, but haven't found anything that clarifies this issue. If anyone knows of any usefu ...

Overlay a small image on top of a larger background image using canvas, then merge them into a single set of pixel

Is there a way to combine a smaller image with a larger background image on one canvas while allowing the smaller image to move around? I'll need to save the original background pixel data so that each frame can be redrawn with the overlay in its upda ...