# Eloquent: Relationships

## Introduction

Database tables are often related to one another. In Laravel Bash, those relationships are joined with `join`, a program from 1979 that does relational joins on sorted text files and that almost nobody has heard of.

## One to Many

```bash
# app/Models/Post.sh
model Post posts
hasMany comments Comment post_id
```

`hasMany` records the relationship: the related model and its foreign key.

### Querying the relationship

```bash
Comment::all | where post_id = 1
```

## Counting Related Models

```bash
Post::all | withCount comments | orderBy comments_count desc | take 3 | table
```

```text
id  title                     comments_count
1   Introducing Laravel Bash  3
4   Queues with mv            3
3   Eloquent is a pipeline    2
```

`withCount` adds a `comments_count` column, which is a `LEFT JOIN ... GROUP BY` in SQL. In Laravel Bash it's two pipelines and `join`:

```bash
join -t $'\t' -a 1 -e 0 -o auto \
  <(sort -t $'\t' -k 1,1) \
  <(Comment::all | pluck post_id | sort | uniq -c | awk -v OFS='\t' '{ print $2, $1 }')
```

1. The posts come in on stdin, sorted by id.
2. `pluck post_id | sort | uniq -c` counts the comments for each post: that's the `GROUP BY`.
3. `join` matches the two on their first field. `-a 1` keeps posts with no comments, which is the `LEFT`. `-e 0` fills the missing count with 0.

> [!WARNING]
> `join` needs both sides sorted the same way, as text. Sorted as numbers, `10` comes after `9`, but `join` expects it to come after `1`, and quietly drops rows. That's why there's a plain `sort` on each side, then `orderBy` afterwards.

## Set Operations

`comm` compares two sorted lists and prints what's only in the first, only in the second, or in both. It's `whereIn` and `whereNotIn`:

```bash
# Posts with no comments
comm -23 <(Post::all | pluck id | sort) <(Comment::all | pluck post_id | sort -u)
```
