在 Laravel 文档中,它说您可以使用此语法来查询对象关系以仅获取具有至少一个评论的帖子:
$posts = Post::has('comments')->get();
我正在尝试类似的方法,我只想获取至少具有一个关系对象的对象。这是我的两个课程:
class Movie extends Eloquent {
protected $table = 'movie';
public function matches() {
return $this->hasMany("Match");
}
}
class Match extends Eloquent {
protected $table = 'match';
public function movie() {
return $this->belongsTo("Movie");
}
}
但是当我打电话
$movies = Movie::has('matches')->get();
我得到一个空集合。如果我打电话
$movie = Movie::find(1)->matches()->get();
我确实得到了与电影相关的匹配,所以我知道关系设置正确。我无法弄清楚我在使用 Movie::has 方法时做错了什么。
我正在使用由 composer 创建的 laravel 项目中包含的 sqlite3 数据库。这是结构和数据:
sqlite> .schema movie
CREATE TABLE "movie" ("id" integer not null primary key autoincrement, "title" varchar not null);
sqlite> .schema match
CREATE TABLE "match" ("id" integer not null primary key autoincrement, "movie_id" integer not null, "title" varchar not null, foreign key("movie_id") references "movie"("id"));
CREATE INDEX match_movie_id_index on "match" ("movie_id");
sqlite> select * from movie;
1|Test Movie
sqlite> select * from match;
1|1|Test Movie Match