> For the complete documentation index, see [llms.txt](https://pckg.gitbook.io/documentation/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://pckg.gitbook.io/documentation/core-packages/index-4/entity/relations.md).

# Relations

* Has many
* Belongs to
* Has and belongs to many
* Has one
* Has parent / Has children

## Has many

When using join, this will result in `... LEFT JOIN posts ON posts.user_id = users.id ...`. With lazy-loading, this will result in `SELECT * FROM posts WHERE user_id = ?`

```php

// ...
use Vendor\Domain\Entity\Posts;
// ...

class Users extends Entity
{
    // ...
    public function posts()
    {
        return $this->hasMany(Posts::class)
            ->foreignKey('user_id');
    }
    // ...
}
```

## Belongs to

When using join, this will result in `... LEFT JOIN groups ON groups.id = users.group_id ...`. With lazy-loading, this will result in `SELECT * FROM groups WHERE id = ?`

```php

// ...
use Vendor\Domain\Entity\Groups;
// ...

class Users extends Entity
{
    // ...
    public function group()
    {
        return $this->belongsTo(Groups::class)
            ->foreignKey('group_id');
    }
    // ...
}
```

## Has many and belongs to (MTM)

When using join, this will result in `... LEFT JOIN friends ON friends.user_id = users.id LEFT JOIN users AS users2 WHERE users2.id = friends.user2_id`. With lazy-loading, this will result in `SELECT * FROM friends WHERE user_id = ?` AND `SELECT * from users WHERE id = ?`.

```php

// ...
use Vendor\Domain\Entity\Friends;
// ...

class Users extends Entity
{
    // ...
    public function friends()
    {
        return $this->hasAndBelongsTo(Users::class)
            ->over(Friends::class)
            ->leftForeignKey('user_id')
            ->rightForeignKey('user2_id');
    }
    // ...
}
```

## Has one

## Has parent / Has children

```php

class Users extends Entity
{
    // ...
    public function parent()
    {
        return $this->hasParent(Users::class)
            ->foreignKey('parent_id');
    }

    public function children()
    {
        return $this->hasChildren(Users::class)
            ->foreignKey('parent_id');
    }
    // ...
}
```

## Morphed by

## Morphs many
