Laravel 변:많은 많은 선택이 없는 항목의 아이들(사용하여 피벗)
문제
예쁜 표준 설정:
테이블의"게시물", 테이블의"종류" 피벗"posts_categories"
/************** CATEGORY MODEL *********/
class Category extends Eloquent
{
/** standard code**/
public function posts()
{
return $this->belongsToMany('Post','posts_categories');
}
}
/************* POSTS MODEL ************/
class Post extends Eloquent
{
/** the usual **/
public function categories()
{
return $this->belongsToMany('Category', 'posts_categories');
}
피벗와 테이블은 적절한 외국 열쇠를 설치됩니다.
하는 그림을 얻는 방법은 모든 게시물이 없는 모든 범주(또는 그 문제에 대한을 얻을 카테고리 없이 게시물에,다음과 같 빈 카테고리)
내가 하고 싶은 것이에는 웅변,그러나 sql 에서 수 다음과 같습니다.
SELECT *,
(SELECT COUNT(id) cnt
FROM posts_categories pc
WHERE pc.post_id = p.id) AS cnt
FROM posts p
HAVING cnt = 0;
해결책
하는 데 사용할 수 있습니다 모든 Posts
는 없 Category
:
$posts = Post::has('categories', '=', 0)->get();
제휴하지 않습니다 StackOverflow