LoginSignup
0
0

More than 3 years have passed since last update.

【Laravel】Eloquentのhasは1階層と2階層両方書く必要はない

Posted at

確認バージョンは 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
)

上記の通り、一階層と二階層両方書く必要はないです!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0