Laravel:查询关系大于0的模型
Laravel: Query the models where the relationship is greater than 0
我正在做一个Laravel查询来查询他的关系大于0的元素列表。
table场音乐会:
| ID | NAME |
|----|-----------|
| 1 | Concert A |
| 2 | Concert B |
| 3 | Concert C |
位置table.
| 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的音乐会。
第二个是我还需要带来所有职位,而不仅仅是查询的职位。
基本上查询只是一种了解我需要带来哪些音乐会的方式。
是否可以通过单个查询实现这一点?
您必须将查询移至 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();
我正在做一个Laravel查询来查询他的关系大于0的元素列表。
table场音乐会:
| ID | NAME |
|----|-----------|
| 1 | Concert A |
| 2 | Concert B |
| 3 | Concert C |
位置table.
| 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的音乐会。 第二个是我还需要带来所有职位,而不仅仅是查询的职位。 基本上查询只是一种了解我需要带来哪些音乐会的方式。
是否可以通过单个查询实现这一点?
您必须将查询移至 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();