Lucid relation in loop

How do i get lucid relation in loop? Record exists

const user = await auth.authenticator('jwt').getUser()
const friends = await Friend.query().where('user_id', user.id).with('user').fetch()

const result = []
for ( let x in friends.rows ) {
	let friend = friends.rows[x]

	result.push({
		'id': friend.friend_id,
		'name': friend.name,
		'profile_pic': friend.user.profile_pic, // Unable to access relation
	})
}
1 Like

hello xpert6
can you please post the content of Friend and User class?

Hi melokki

User class

'use strict'

class User extends Model {

  friends () {
    return this.hasMany('App/Models/Friend', 'id', 'user_id')
  }

}

module.exports = User

Friend class

'use strict'

const Model = use('Model')

class Friend extends Model {
	user () {
	  return this.belongsTo('App/Models/User', 'friend_id', 'id')
	}
}

module.exports = Friend

Friends database schema

CREATE TABLE `friends` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `user_id` int(10) unsigned NOT NULL,
  `friend_id` int(10) unsigned NOT NULL,
  `name` varchar(255) NOT NULL,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `user` (`user_id`),
  KEY `friend` (`friend_id`),
  CONSTRAINT `friend` FOREIGN KEY (`friend_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `user` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1
1 Like

It should be friend.getRelated('user').profile_pic

1 Like

Thanks virk, that works but now i cant access the computed property. Is there any way?

static get computed () {
  return ['profile_pic_url']
}

getProfilePicUrl()
{
    return this.profile_pic ? this.profile_pic : ThemeHelper.public_url(Config.get('constants.front.dir.profilePicPath') + Config.get('constants.front.default.profilePic'));
}
1 Like

I recommend you to read the docs. The computed properties are evaluated when you run toJSON() on a model instance

2 Likes

Hi, i also have same issues, i can’t looping eagar loading data. I am getting only function