编程语言
首页 > 编程语言> > php – Laravel查询关系模型:: has(‘relation’)不起作用

php – Laravel查询关系模型:: has(‘relation’)不起作用

作者:互联网

在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作为数据库驱动程序时,返回一个空集合,因为计数包含在引号中.您可以使用DB :: raw方法将计数作为原始表达式传递.

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

相关问题:#3353,#3435.

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

标签:php,laravel-4,database-relations,querying
来源: https://codeday.me/bug/20190517/1120774.html