modeltyper icon indicating copy to clipboard operation
modeltyper copied to clipboard

Add _count and _exists relation properties

Open joelstein opened this issue 1 year ago • 3 comments

What do you think about a feature that includes relation properties for the withCount() and withExists() Laravel methods?

Such a feature would generate a Typescript definition like this:

export interface User {
  // columns
  id: number
  name: string
  // relations
  posts: Post[]
  posts_count: int
  posts_exists: bool
}

joelstein avatar Feb 15 '25 13:02 joelstein

i think we had them in a earlier version, but i didn't find to much use for them myself, happy to accept a PR that adds this with a optional flag to set these values.

tcampbPPU avatar Feb 17 '25 17:02 tcampbPPU

You might also be able to do this with some TS generics:

interface User {
  // columns
  id: number
  name: string
  // relations
  posts: WithRelationExtras<Post>
}

interface Post {
  id: number
  title: string
}


// Generic to generate counts and exists...
interface WithRelationExtras<T> extends Array<T> {
  get count(): number;
  get exists(): boolean;
}

Object.defineProperty(Array.prototype, 'count', {
  get: function() {
    return this.length;
  }
});

Object.defineProperty(Array.prototype, 'exists', {
  get: function() {
    return this.length > 0;
  }
});

// create user with posts
const user: User = {
  id: 1,
  name: 'John Doe',
  posts: [
    { id: 1, title: 'Foo' },
    { id: 2, title: 'Bar' },
  ] as WithRelationExtras<Post>,
}

console.log(user.posts)

tcampbPPU avatar Feb 17 '25 17:02 tcampbPPU

This issue is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 5 days.

github-actions[bot] avatar Mar 20 '25 02:03 github-actions[bot]

#96 I have submitted a pull request. Please take a look at it.

bishwajitcadhikary avatar Jun 12 '25 18:06 bishwajitcadhikary

Thanks @bishwajitcadhikary! It appears that this issue has been merged, so I believe we can close this ticket.

joelstein avatar Jun 16 '25 15:06 joelstein