Laavel에서 관계 없는 데이터만 가져오기

안녕하세요.
이번에는 라벨에서 상관 없는 데이터만 얻는 방법에 대해 설명한다.
이번 구상은 articlescomments 두 개의 테이블이 있는데, 나는 논평이 없는 보도만 얻으려고 한다.

댓글 없는 글만 가져오기


whereDoesnthave 사용 방법


with comments도 함께 얻은 후에articleId와 일치하는 comments에 없는 것만 얻었다는 논리다.
public function getArticlesWithoutComments(int $articleId)
{
    return Article::with("comments")->whereDoesntHave('comments')->get();
}
관계 데이터에 조건을 추가하려면whereDoesntHave의 두 번째 매개 변수에 조건을 추가할 수 있습니다.
예를 들어, 사용자 ID를 사용하여 조건을 제한해 봅니다.
public function getArticlesWithoutComments(int $articleId, int $userId)
{
    return Article::with("comments")->whereDoesntHave('comments', function ($q) use ($userId) {
            $q->where('user_id', $userId);
        })->get();
}

withCount과 having의 조합을 사용하는 방법


with 추가 조건으로 검색 결과 수가 0의 논리를 얻습니다.
public function getArticlesWithoutComments(int $articleId)
{
    return Article()::withCount('comments')
        ->having('comments_count', 0)
        ->get();
}
withCount를 만들면 관계 데이터의 계수는'XXX count'이라는 이름으로 나오기 때문에 상대적인 having은 0의 계수만 얻는다.
withCount도 with와 마찬가지로 조건을 붙일 수 있다.
아까와 마찬가지로 댓글의userId에 조건을 붙여주세요.
public function getArticlesWithoutComments(int $articleId, int $userId)
{
    return Article()::withCount(['comments' => function($q) use ($userId) {
        $q->where('user_id', $userId);
    }])
        ->having('comments_count', 0)
        ->get();
}
이상의 느낌으로 관계 없는 데이터를 얻었다.

좋은 웹페이지 즐겨찾기