確認バージョンは Laravel 7.26.1
例えばこんなモデルがあったとすると
class User extends Authenticatable
{
/**
* Relations
*/
public function posts()
{
return $this->hasMany(Post::class);
}
public function comments()
{
return $this->hasMany(Comment::class);
}
}
class Post extends Model
{
use SoftDeletes;
/**
* Relations
*/
public function user()
{
return $this->belongsTo(User::class);
}
public function comments()
{
return $this->hasMany(Comment::class);
}
}
class Comment extends Model
{
const UPDATED_AT = null;
/**
* Relations
*/
public function user()
{
return $this->belongsTo(User::class);
}
public function post()
{
return $this->belongsTo(Post::class);
}
}
一階層のhas
User::has('posts')->get();
select * from users
where exists (
select * from posts
where users.id = posts.user_id
and posts.deleted_at is null
)
二階層のhas
User::has('posts.comments')->get();
select * from users
where exists (
select * from posts
where users.id = posts.user_id
and exists (
select * from comments
where posts.id = comments.post_id
)
and posts.deleted_at is null
)
一階層&二階層のhas
User::has('posts')
->has('posts.comments')
->get();
select * from users
where exists (
select * from posts
where users.id = posts.user_id
and posts.deleted_at is null
)
and exists (
select * from posts
where users.id = posts.user_id
and exists (
select * from comments
where posts.id = comments.post_id
)
and posts.deleted_at is null
)
上記の通り、一階層と二階層両方書く必要はないです!