1$comment = Post::find(1)->comments()
2 ->where('title', 'foo')
3 ->first();
1return $this->hasMany(Comment::class, 'foreign_key');
2
3return $this->hasMany(Comment::class, 'foreign_key', 'local_key');
1/**
2 * Get the user's most recent order.
3 */
4public function latestOrder()
5{
6 return $this->hasOne(Order::class)->latestOfMany();
7}
1class Project extends Model
2{
3 public function deployments()
4 {
5 return $this->hasManyThrough(
6 Deployment::class,
7 Environment::class,
8 'project_id', // Foreign key on the environments table...
9 'environment_id', // Foreign key on the deployments table...
10 'id', // Local key on the projects table...
11 'id' // Local key on the environments table...
12 );
13 }
14}
1/**
2 * Get the current pricing for the product.
3 */
4public function currentPricing()
5{
6 return $this->hasOne(Price::class)->ofMany([
7 'published_at' => 'max',
8 'id' => 'max',
9 ], function ($query) {
10 $query->where('published_at', '<', now());
11 });
12}
1<?php
2
3namespace App\Models;
4
5use Illuminate\Database\Eloquent\Model;
6
7class Comment extends Model
8{
9 /**
10 * Get the post that owns the comment.
11 */
12 public function post()
13 {
14 return $this->belongsTo(Post::class);
15 }
16}
1/**
2 * Get the user's oldest order.
3 */
4public function oldestOrder()
5{
6 return $this->hasOne(Order::class)->oldestOfMany();
7}
1use App\Models\User;
2
3$user = User::find(1);
4
5foreach ($user->roles as $role) {
6 //
7}
1<?php
2
3namespace App\Models;
4
5use Illuminate\Database\Eloquent\Model;
6
7class Mechanic extends Model
8{
9 /**
10 * Get the car's owner.
11 */
12 public function carOwner()
13 {
14 return $this->hasOneThrough(Owner::class, Car::class);
15 }
16}