Laravel查询关系模型:: has('relation')不起作用 [英] Laravel Querying Relations Model::has('relation') doesn't work

查看:408
本文介绍了Laravel查询关系模型:: has('relation')不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Laravel文档中,您可以使用此语法查询对象关系,以仅获取具有至少一个注释的帖子:

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:

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

但是当我打电话

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

我得到一个空的收藏集.如果我打电话

I get an empty collection. If I call

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

我确实获得了与电影相关的Match,因此我知道该关系已正确设置.我无法弄清楚Movie :: has方法在做什么.

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.

我正在使用用composer创建的laravel项目中包含的sqlite3数据库.这是结构和数据:

I'm using the sqlite3 database included with a laravel project created with composer. 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

推荐答案

但是,这在MySQL驱动程序中可以正常使用.当使用SQLite作为数据库驱动程序时,has返回一个空集合,因为计数用引号引起来.您可以使用DB::raw方法将计数作为原始表达式传递.

This however works fine with the MySQL driver. When using SQLite as the database driver, has returns an empty collection because the count gets wrapped in quotes. You may use the DB::raw method to pass the count as a raw expression.

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

相关问题:#3353 patricus 确认此问题仅影响Laravel 4.1.25之前的安装.您无需在较新的版本中使用此替代方法.

As patricus affirmed this issue was affecting only installations prior to Laravel 4.1.25. You don't need to use this workaround with newer versions.

这篇关于Laravel查询关系模型:: has('relation')不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆