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

Using VueJS for Dynamic Class Binding

Using Vue version 3.0.5. I have a component named Cube.vue where I am attempting to dynamically assign a blue or green class to a child element. The component has been created and imported into a specific page, however, I am facing issues getting the con ...

The proper way to cancel useEffect's Async in TypeScript

I'm facing an issue with this straightforward example: useEffect(() => { axios.get(...).then(...).catch(...) }, [props.foo]) warning: can't perform a react state update on an unmounted component After some investigation, I found this ...

JavaScript's square bracket notation is commonly used to access nested objects within an object

My goal is to accomplish the following: this.inputs[options.el.find('form').attr('class')] = {}; this.inputs[options.el.find('form').attr('class')][options.elements[x].selector] = false; Unfortunately, I'm fa ...

Can you identify any issues with this Basic authentication code for an HTTP-Get request?

My setup consists of node.js restify as the backend for running a REST API server, and angularjs as the front-end for making HTTP GET calls. The REST server is configured with HTTP Basic Authentication using the username foo and password bar. To confirm t ...

How can I utilize columns from a junction table in the "where" clause in sequelize?

Looking to execute a Sequelize query on multiple related models: SELECT Cou.country_id, cou.country_name, Sta.state_id, Sta.state_name, Dis.district_id, Dis.district_name, Cit.city_id, Cit.city_name, Loc.location_id, Loc.location_name, Sub_Loc.sub_locatio ...

Is there a way to make images load only when the navigation buttons are clicked in a scrollable (jquery tools) rather than loading all images at once?

I came across this great demo tutorial that I'm currently following: The issue with the tutorial is that it loads all the images at once, which significantly impacts performance. My goal is to have it load a set of images each time you click the arro ...

Crafting a dynamic bar chart with recharts for your data visualization

Is it possible to set a custom bar range in the Bar Chart made with recharts? Can we define specific start and end positions for the bars? For instance, if I have two values startPos and endPos, is there a way to create a Bar that starts at startPos and e ...

Exploring the power of TypeScript within the useContext hook

I recently started following a React tutorial on YouTube and decided to convert the project from JavaScript to TypeScript. However, I am facing difficulties with implementing useContext in my code. Any help or guidance would be greatly appreciated. If yo ...

Form Validation in JavaScript Continues to Submit Form Even When 'False' is Detected

Here is the issue at hand - I am restricted to using older browsers (IE8 and FF8) by corporate policy. Despite my research indicating otherwise, it seems like this might be the root cause of my troubles. My current setup includes PHP 5.5.12 on Apache 2.4. ...

What are the steps for releasing a Next.js app as an npm package?

Currently, my web application is developed using Next.js. I am interested in distributing it as an npm package for others to utilize in their projects. Despite my efforts to search and seek assistance through Google, I have not come across any valuable ins ...

Having trouble with importing a variable in an Express application? You may encounter this error message: "Route.get() must

When trying to import requireSignin from the controllers/auth.js file into the routes/user.js file and adding it to the router.get('/user/:id', requireSignin, read); route, an error occurs: Error: Route.get() requires a callback function but r ...

"Using Node.js to create a simulated mobile environment: a step-by-step guide

I am seeking a way to replicate the functionalities of a mobile browser using Node.js. This means that all mobile browser features should be accessible on the client-side, even if they are simulated. The goal is for webpages to believe they are being load ...

"Utilize TipTap with the power of your personalized name

Is it feasible to work around the inability to use the name tag on TipTap for sending data through forms in Laravel? Here's an example of what I have in mind: <tiptap-vuetify v-model="content" :extensions="extensions" ...

Send the form via ajax

I am in the process of creating a unique application for my university, which is essentially a social network. One key feature I need to implement is the ability for users to add comments, which involves inserting a row into a specific database. To achieve ...

AngularJS - Regular Expression Error

I have implemented a RegEx pattern to validate passwords entered by users. The password must contain at least 1 capital letter, 1 number, and 1 symbol: /(?=.*?\d)(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[^a-zA-Z\d])/ When this RegEx is used with ng-patter ...

Turning an Array of Objects into a typical JavaScript Object

Below are arrays of numbers: var stats = [ [0, 200,400], [100, 300,900],[220, 400,1000],[300, 500,1500],[400, 800,1700],[600, 1200,1800],[800, 1600,3000] ]; I am seeking guidance on how to transform it into the JavaScript object format shown below. ...

What is the best method to retrieve a secure httponly cookie in a Next.js application?

Our next JS application is making a request to The backend team has configured the response cookie as a secure HttpOnly cookie. const session = await ( await fetch( `https://demo.com/auth/session`, requestOptions )).json(); console.log(&qu ...

Issue in Vue.js: Struggling to compile SASS styles for an HTML element generated dynamically

I'm working with a basic Vue.js component where I'm rendering a snippet of HTML: ... <div class="sml-button" v-on:click="toggleButton()" v-html="button"></div> ... When the button is clicked, the toggleButton() function updates the ...

Struggling to add a line break in my code

class Test extends React.Component{ state={name: "John", numTimes: 2}; render() { let output = "" for (let i = 1; i <= this.state.numTimes; i++) { let evenOdd = i % 2 if (evenOdd === 0) { output += i + ". Hello " + this.state.name + ...

Is there a way to extract a token from the URL in a Nextjs/React application?

I am currently developing a project that relies heavily on API integration. My front-end interface is built using React and Next.js, while the back-end API is developed with Laravel. Within my front-end page, I have implemented a token in the URL to help ...