Eloquent ORM
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
# 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
Comment::all | where post_id = 1
Counting Related Models
Post::all | withCount comments | orderBy comments_count desc | take 3 | table
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:
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 }')
- The posts come in on stdin, sorted by id.
pluck post_id | sort | uniq -ccounts the comments for each post: that's theGROUP BY.joinmatches the two on their first field.-a 1keeps posts with no comments, which is theLEFT.-e 0fills 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:
# Posts with no comments
comm -23 <(Post::all | pluck id | sort) <(Comment::all | pluck post_id | sort -u)