question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Can I define accessor with model?

See original GitHub issue

I want define accessor with model object like Laravel eloquent accessor. https://laravel.com/docs/5.6/eloquent-mutators#accessors-and-mutators

Is it possbile?

export default class Person extends Model {
  defaults() {
    return {
      id: null,
      firstName: '',
      lastName: ''
    };
  }

  get fullname() {
    return `${this.lastName} ${this.firstName} `;
  }
}

const person = new Person({firstName: 'Shu', lastName: 'Ogawa'});
console.log(person.fullname); // Ogawa Shu

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:5 (1 by maintainers)

github_iconTop GitHub Comments

1reaction
shuogawacommented, Aug 21, 2018

@sifex Thank you for reply.

I tried. But fullname is empty.

import { Model } from 'vue-mc';
export default class Person extends Model {
  defaults() {
    return {
      id: null,
      firstName: '',
      lastName: ''
    };
  }

  mutations() {
    return {
      fullName: () => 'this is dynamic field'
    };
  }
}

Screenshot from Gyazo

I had check by vue devtool. _mutations is empty object.

Screenshot from Gyazo

Where is wrong?

0reactions
alvaro-canepacommented, Jan 15, 2021

I made my own accessors method, based on mutations.

import Vue from "vue";
import { Model as BaseModel } from "vue-mc";
import _ from "lodash";

export default class Model extends BaseModel {
  _accessors!: Record<string, Accessor>;

  boot() {
    Vue.set(this, "_accessors", {});
    this.compileAccessors();
  }

  /**
   *  @returns {Object} Attribute accessor keyed by attribute name.
   */
  accessors(): Record<string, Accessor | Accessor[]> {
    return {};
  }

  /**
   * Compiles all accessors into pipelines that can be executed quickly.
   */
  compileAccessors(): void {
    this._accessors = _.mapValues(
      this.accessors(),
      (m: Accessor | Accessor[]): Accessor => _.flow(m as Accessor[])
    );

    this.on("sync", this.assignAccessors);
  }

  /**
   * Sync all accessors with model attributes
   */
  assignAccessors(): void {
    _.each(this._accessors, (fAccessor: Accessor, sKey) => {
      this.set(sKey, fAccessor());
    });
  }
}

export type Accessor = (value?: any) => any;

How to use

import Model from './Model';
import _ from "lodash";

export default class Person extends Model {
  defaults() {
    return {
      id: null,
      firstName: '',
      lastName: ''
    };
  }

  accessors() {
    return {
      fullName: () => {
        return _.chain([this.firstName, this.lastName])
          .compact()
          .join(" ")
          .value();
      }
    };
  }
}

const person = new Person({firstName: 'Shu', lastName: 'Ogawa'});
console.log(person.fullName); // Ogawa Shu
Read more comments on GitHub >

github_iconTop Results From Across the Web

How to define an accessor in model where the field name ...
I am trying to define an accessor in my User model for a field which already exists. This field is called address_line_1 in...
Read more >
How can I query using Accessor that I defined in Model
How can I query using Accessor that I defined in Model ; public function getStatusAttribute() ; $this->loss == 0 ; $this->loss > $this...
Read more >
Model Accessors & Mutators - LdapRecord
Accessors and mutators allow you to modify attribute values when you retrieve or set them on model instances. If you'd ever used Laravel ......
Read more >
Laravel 8 - Accessors and Mutators (Eloquent in 2 Steps)
To define an accessor, create a get{Attribute}Attribute method on your model where {Attribute} is the “studly” cased name of the column. Open ...
Read more >
Eloquent: Mutators - The PHP Framework For Web Artisans
Accessors and mutators allow you to format Eloquent attribute values when you retrieve or set them on model instances. For example, you may...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found