# 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


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://pckg.gitbook.io/documentation/core-packages/index-4/entity/relations.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
