Laavel에서 관계 없는 데이터만 가져오기
8148 단어 Laravelrelationshiptech
이번에는 라벨에서 상관 없는 데이터만 얻는 방법에 대해 설명한다.
이번 구상은
articles
과 comments
두 개의 테이블이 있는데, 나는 논평이 없는 보도만 얻으려고 한다.댓글 없는 글만 가져오기
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();
}
이상의 느낌으로 관계 없는 데이터를 얻었다.
Reference
이 문제에 관하여(Laavel에서 관계 없는 데이터만 가져오기), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://zenn.dev/naoki_oshiumi/articles/2734fc15a14154텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)