Eloquent Models with relationships for lucadegasperi/oauth2-server-laravel

85 Views Asked by At

anyone has actual Eloquent Models for the lucadegasperi/oauth2-server-laravel package. Migrations are not very clear on the relationships, especially Many-to-Many. Not sure which side should be hasMany() vs belongsToMany(). Trying to follow the migrations to make models for Neo4j databases.

1

There are 1 best solutions below

1
On

When it comes to relationships, given that all relations in Neo4j are directed:

  • hasMany is an OUTGOING relationship (node1)-[:REL]->(node2) where node1 can have multiple outgoing relationships of that kind
  • belongsToMany is an INCOMING relationship (node1)<-[:INCOME]-(node2) where node1 can have multiple incoming relationships of that kind

node1 represents a model with a label (i.e. User) having relations such as Post (hasMany) and Tag (belongsToMany posts) so you'll have to define your relationships inside the model class as follows

class User
{
    public function posts()
    {
        return $this->hasMany(Post::class, 'POSTED');
    }
}

class Post
{
    public function user()
    {
        // reverse of "posts" and must have the same name "POSTED"
        return $this->belongsTo(User::class, 'POSTED'); 
    }

    public function tags()
    {
        return $this->hasMany(Tag::class, 'TAGGED_WITH');
    }
}

class Tag
{
    public function posts()
    {
        // reverse of "tags" and must have the same name "TAGGED_WITH"
        return $this->belongsToMany(Post::class, 'TAGGED_WITH');
    }
}

You'll end up with the following:

  • (:User)-[:POSTED]->(:Post)
  • (:Post)-[:TAGGED_WITH]->(:Tag)

And you'll be able to refer to any node from any side.

I haven't used the package lucadegasperi/oauth2-server-laravel but in case they have instructions on how the relationships between models should be, you should be good to go.