1class Country extends Model
2{
3 public function posts()
4 {
5 return $this->hasManyThrough(
6 'App\Post',
7 'App\User',
8 'country_id', // Foreign key on users table...
9 'user_id', // Foreign key on posts table...
10 'id', // Local key on countries table...
11 'id' // Local key on users table...
12 );
13 }
14}
15
16when
17countries
18 id - integer
19 name - string
20
21users
22 id - integer
23 country_id - integer
24 name - string
25
26posts
27 id - integer
28 user_id - integer
29 title - string
1 public function comments()
2 {
3 return $this->hasMany(Comment::class);
4 }
1For example, a blog post may have an infinite number of comments. And a single
2comment belongs to only a single post
3
4class Post extends Model
5{
6 public function comments()
7 {
8 return $this->hasMany('App\Models\Comment');
9 }
10}
11
12class Comment extends Model
13{
14 public function post()
15 {
16 return $this->belongsTo('App\Models\Post');
17 }
18}
1<?php
2
3namespace App\Models;
4
5use Illuminate\Database\Eloquent\Model;
6
7class Post extends Model
8{
9 /**
10 * Get the comments for the blog post.
11 */
12 public function comments()
13 {
14 return $this->hasMany('App\Models\Comment');
15 }
16}
1$movies = Movie::whereHas('director', function($q) {
2 $q->where('name', 'great');
3})->get();
4