Laravel:查询关系大于0的模型

时间:2019-04-18 00:31:21

标签: laravel laravel-5 eloquent laravel-5.8

我正在执行Laravel查询,以查询其关系大于0的元素列表。

演唱会:

| ID |    NAME   |
|----|-----------|
| 1  | Concert A |
| 2  | Concert B |
| 3  | Concert C |

还有排名表。

| ID |  concert_id    |   user_id  | Content  |
|----|----------------|------------|----------|
| 1  |       1        |      1     |    xxx   |
| 2  |       1        |      2     |    yyy   |
| 3  |       3        |      1     |    zzz   |
| 4  |       3        |      2     |    www   |
| 5  |       1        |      3     |    xyx   |
| 6  |       3        |      3     |    rer   |

我需要做的查询是,获取音乐会在其内容中具有$some_query$之类的值。

我的代码如下:

$result = $this->model->whereHas('positions')
    ->with(['positions' => function ($query) {
        $query->where('content', 'like', "%{$content}%");
    }])->get();

但是据我所知,这将带来所有音乐会,而且还将带来仅具有所需内容的职位。

所以我有两个问题,第一个是我需要让他的查询位置大于0的音乐会。 第二个是我还需要担任所有职务,而不仅仅是被查询的职务。 基本上,查询只是一种了解我需要带哪些音乐会的方式。

是否可以通过单个查询来实现?

1 个答案:

答案 0 :(得分:0)

您必须将查询移至whereHas

如果我理解得很好,这就是您想要的:

$result = $this->model
    // Take the Concerts that has positions with a similar content
    ->whereHas('positions', function ($query) use ($content) {
        $query->where('content', 'like', "%{$content}%");
    })
    // Take (all) the Positions of these concerts
    ->with('positions')
    ->get();
相关问题