简体   繁体   English

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

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

In the Laravel documentation it says you can use this syntax for querying an object relation to get only the Posts that have at least one Comment: 在Laravel文档中,它说你可以使用这种语法来查询对象关系,只获得至少有一个Comment的帖子:

$posts = Post::has('comments')->get();

I'm trying something similar where I want to fetch only objects that have at least one relation object. 我正在尝试类似的东西,我只想获取至少有一个关系对象的对象。 These are my two classes: 这是我的两个班级:

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");
    }
}

But when I call 但是当我打电话时

$movies = Movie::has('matches')->get();

I get an empty collection. 我得到一个空集合。 If I call 如果我打电话

$movie = Movie::find(1)->matches()->get();

I do get the Match that relates to the Movie, so I know the relation is setup properly. 我确实得到了与电影相关的匹配,所以我知道关系设置正确。 I can't figure out what I'm doing wrong with the Movie::has method though. 我无法弄清楚我在使用Movie :: has方法做错了什么。

I'm using the sqlite3 database included with a laravel project created with composer. 我正在使用随composer创建的laravel项目中包含的sqlite3数据库。 This is the structure and data: 这是结构和数据:

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

This however works fine with the MySQL driver. 然而,这适用于MySQL驱动程序。 When using SQLite as the database driver, has returns an empty collection because the count gets wrapped in quotes. 当使用SQLite作为数据库驱动程序, has返回空集,因为计数被包裹在引号。 You may use the DB::raw method to pass the count as a raw expression. 您可以使用DB::raw方法将计数作为原始表达式传递。

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

Related issues: #3353 , #3435 . 相关问题: #3353#3435

Edit: As patricus affirmed this issue was affecting only installations prior to Laravel 4.1.25. 编辑:由于patricus肯定这个问题只影响Laravel 4.1.25之前的安装。 You don't need to use this workaround with newer versions. 您不需要在较新版本中使用此变通方法。

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

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