如何构建 Eloquent 查询以检索主 table 的记录,并在 Laravel 5 PHP 中对其相关的 table 应用 where 子句?
How to build Eloquent query to retrieve records of the main table, applying where clause on it's related table in Laravel 5 PHP?
使用 Laravel 文档中的示例多对多多态关系数据库结构如下:
posts
id - integer
name - string
videos
id - integer
name - string
tags
id - integer
name - string
taggables
tag_id - integer
taggable_id - integer
taggable_type - string
我想检索 post
条记录,其中 post.name LIKE %laravel%
或 tags.name LIKE %laravel%
。
如何使用 Eloquent 模型来构建这样的查询?这对我来说是一个很大的挑战,因为我只想获得其名称由单词 laravel
组成的帖子或者其相关标签的名称由相同单词组成的任何帖子。
您可以为此使用 whereHas
。
来自docs:
If you need even more power, you may use the whereHas and orWhereHas
methods to put "where" conditions on your has queries. These methods
allow you to add customized constraints to a relationship constraint,
such as checking the content of a comment
use Illuminate\Database\Eloquent\Builder;
// Retrieve posts with at least one comment containing words like foo%...
$posts = App\Post::whereHas('comments', function (Builder $query) {
$query->where('content', 'like', 'foo%');
})->get();
在你的情况下它会是这样的:
use Illuminate\Database\Eloquent\Builder;
$input = 'laravel';
Post::whereHas('tags', function (Builder $query) use ($input) {
$query->where('name', 'like', '%' . $input .'%');
})->orWhere('name', 'like', '%' . $input . '%')->get();
这应该有效:
$result = Post::whereHas('tags', function ($query) {
$query->where('name', 'like', '%laravel%')
->orWhere('tags.name', 'like', '%laravel%');
})->get();
使用 Laravel 文档中的示例多对多多态关系数据库结构如下:
posts
id - integer
name - string
videos
id - integer
name - string
tags
id - integer
name - string
taggables
tag_id - integer
taggable_id - integer
taggable_type - string
我想检索 post
条记录,其中 post.name LIKE %laravel%
或 tags.name LIKE %laravel%
。
如何使用 Eloquent 模型来构建这样的查询?这对我来说是一个很大的挑战,因为我只想获得其名称由单词 laravel
组成的帖子或者其相关标签的名称由相同单词组成的任何帖子。
您可以为此使用 whereHas
。
来自docs:
If you need even more power, you may use the whereHas and orWhereHas methods to put "where" conditions on your has queries. These methods allow you to add customized constraints to a relationship constraint, such as checking the content of a comment
use Illuminate\Database\Eloquent\Builder;
// Retrieve posts with at least one comment containing words like foo%...
$posts = App\Post::whereHas('comments', function (Builder $query) {
$query->where('content', 'like', 'foo%');
})->get();
在你的情况下它会是这样的:
use Illuminate\Database\Eloquent\Builder;
$input = 'laravel';
Post::whereHas('tags', function (Builder $query) use ($input) {
$query->where('name', 'like', '%' . $input .'%');
})->orWhere('name', 'like', '%' . $input . '%')->get();
这应该有效:
$result = Post::whereHas('tags', function ($query) {
$query->where('name', 'like', '%laravel%')
->orWhere('tags.name', 'like', '%laravel%');
})->get();