Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

how to hiding "pivot" attribute from belongsToMany relationships? #366

Closed
italoiz opened this issue Aug 9, 2018 · 7 comments
Closed

how to hiding "pivot" attribute from belongsToMany relationships? #366

italoiz opened this issue Aug 9, 2018 · 7 comments
Assignees
Labels
Priority: Medium Try to fix the issue for the next patch/minor release Semver: Alpha Will make it's way to the next alpha version of the package Type: Enhancement Improving an existing feature

Comments

@italoiz
Copy link
Contributor

italoiz commented Aug 9, 2018

I have a belongsToMany relationship, but I'd like to hide the "pivot" attribute of the output in JSON.

@thetutlage
Copy link
Member

Can you share the code you are running?

@italoiz
Copy link
Contributor Author

italoiz commented Oct 1, 2018

I have model with code below:

A Class related to Courses, Students and Teachers.

'use strict'

const Model = use('Model')

class Class extends Model {
  /**
   * Filter by class.
   *
   * @param {*} query
   * @param {*} type
   */
  static scopeByClass (query, class_id) {
    if (class_id) {
      if (class_id instanceof Array) {
        query.whereIn('id', class_id)
      } else {
        query.where('id', class_id)
      }
    }
  }

  /**
   * Filter by course.
   *
   * @param {*} query
   * @param {*} type
   */
  static scopeByCourse (query, course_id) {
    if (course_id) {
      query.whereHas('courses', query => {
        if (course_id instanceof Array) {
          query.whereIn('course_id', course_id)
        } else {
          query.where('course_id', course_id)
        }
      })
    }
  }

  /**
   * Filter by teacher.
   *
   * @param {*} query
   * @param {*} type
   */
  static scopeByTeacher (query, teacher_id) {
    if (teacher_id) {
      query.whereHas('teachers', query => {
        if (teacher_id instanceof Array) {
          query.whereIn('user_id', teacher_id)
        } else {
          query.where('user_id', teacher_id)
        }
      })
    }
  }

  /**
   * Teachers.
   *
   * @return Array<User>
   */
  teachers () {
    // return this.hasMany('App/Models/ClassTeacher')
    return this.belongsToMany('App/Models/User').pivotModel(
      'App/Models/ClassTeacher'
    )
  }

  /**
   * Courses.
   *
   * @return Array<Course>
   */
  courses () {
    return this.belongsToMany('App/Models/Course').pivotModel(
      'App/Models/ClassCourse'
    )
  }

  /**
   * Students
   *
   * @return Array<User>
   */
  students () {
    return this.belongsToMany('App/Models/User').pivotModel(
      'App/Models/UserClass'
    )
  }
}

module.exports = Class

On my method index() of controller:

  async index ({ request, response, view }) {
    const {
      page,
      class: class_id,
      course: course_id,
      teacher: teacher_id
    } = request.get()

    const classes = await Class.query()
      .orderBy('created_at', 'DESC')
      .with('teachers')
      .with('courses')
      .with('students')
      .withCount('teachers as total_teachers')
      .withCount('courses as total_courses')
      .withCount('students as total_students')
      .byClass(class_id)
      .byCourse(course_id)
      .byTeacher(teacher_id)
      .paginate(page)

    return classes
  }

And object received in response of request:

{
	"total": 2,
	"perPage": 20,
	"page": 1,
	"lastPage": 1,
	"data": [
		{
			"id": 15,
			"title": "The title",
			"description": "The class description",
			"created_at": "2018-08-09 01:47:22",
			"updated_at": "2018-08-09 01:47:22",
			"teachers": [
				{
					"id": 8,
					"username": "username",
					"first_name": "first_name",
					"last_name": "last_name",
					"pivot": {
						"user_id": 8,
						"class_id": 15
					}
				}
			],
			"courses": [
				{
					"id": 2,
					"title": "Title",
					"description": "The course description",
					"created_at": "2018-08-09 00:52:40",
					"updated_at": "2018-08-09 00:52:40",
					"pivot": {
						"course_id": 2,
						"class_id": 15
					}
				}
			],
			"students": [
				{
					"id": 9,
					"username": "username",
					"first_name": "first_name",
					"last_name": "last_name",
					"pivot": {
						"user_id": 9,
						"class_id": 15
					}
				}
			],
			"__meta__": {
				"total_teachers": 1,
				"total_courses": 1,
				"total_students": 1
			}
		}
	]
}

I would like to hide the "pivot" object within the relationships in the objects "teachers", "students", "courses"...

If you have any questions, let me know! Thank you.

@thetutlage
Copy link
Member

Ahh okay. I don't think it's possible right now. Within the pivot model you can set hidden fields user_id and class_id, but that will not remove the top level pivot key from the object.

I will add this to the enhancements and will try to work on it later

@Dysanix
Copy link

Dysanix commented Nov 12, 2018

Just dropping by to show my support for this Enhancement-request.

@thetutlage
Copy link
Member

The newer release of AdonisJs Lucid @adonisjs/[email protected] will exclude all pivot columns by default and one can add them by creating a computed property (if required).

Let's imagine, you want to include the pivot object along with the course id. It can be done as follows:

class Teacher extends Model {
  get pivot () {
    if (this.$extras.pivot_course_id) {
      return {
        course_id: this.$extras.pivot_course_id
      }
    }
  }
}

@thetutlage thetutlage added Priority: Medium Try to fix the issue for the next patch/minor release Semver: Alpha Will make it's way to the next alpha version of the package Status: Completed The work has been completed, but not released yet Type: Enhancement Improving an existing feature labels Nov 7, 2019
@stale
Copy link

stale bot commented Jul 9, 2020

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

@stale stale bot added the wontfix label Jul 9, 2020
@stale stale bot closed this as completed Jul 16, 2020
@thetutlage thetutlage removed the Status: Completed The work has been completed, but not released yet label Jul 16, 2020
@ymsaadi
Copy link

ymsaadi commented Apr 22, 2021

It's back to showing the pivot field by default, is it a bug ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Priority: Medium Try to fix the issue for the next patch/minor release Semver: Alpha Will make it's way to the next alpha version of the package Type: Enhancement Improving an existing feature
Projects
None yet
Development

No branches or pull requests

4 participants