在 Laravel 文档中它说您可以使用此语法查询对象关系以仅获取至少有一个评论的帖子:
$posts = Post::has('comments')->get();
我正在尝试类似的方法,我只想获取至少具有一个关系对象的对象。这是我的两个类(class):
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
最佳答案
然而,这对 MySQL 驱动程序来说工作得很好。当使用 SQLite 作为数据库驱动程序时,has
返回一个空集合,因为计数被引号括起来了。您可以使用 DB::raw
方法将计数作为原始表达式传递。
$posts = Post::has('comments', '>=', DB::raw(1))->get();
编辑:作为patricus确认此问题仅影响 Laravel 4.1.25 之前的安装。您不需要将此解决方法用于较新的版本。
关于php - Laravel 查询关系模型::有 ('relation' ) 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20714559/