繁体   English   中英

Laravel查询关系模型:: has('relation')不起作用

[英]Laravel Querying Relations Model::has('relation') doesn't work

在Laravel文档中,它说你可以使用这种语法来查询对象关系,只获得至少有一个Comment的帖子:

$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

然而,这适用于MySQL驱动程序。 当使用SQLite作为数据库驱动程序, has返回空集,因为计数被包裹在引号。 您可以使用DB::raw方法将计数作为原始表达式传递。

$posts = Post::has('comments', '>=', DB::raw(1))->get();

相关问题: #3353#3435

编辑:由于patricus肯定这个问题只影响Laravel 4.1.25之前的安装。 您不需要在较新版本中使用此变通方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM