crhg/eloquent-exists-relation
Composer 安装命令:
composer require crhg/eloquent-exists-relation
包简介
Add withExits method to check existence of related records with subquery.
README 文档
README
Add an attribute that indicates whether there is an element indicated by the relation specified when acquiring to the Eloquent Model using a subquery.
It is similar to withCount, which finds the number of elements of a relation, but it differs in obtaining only whether it exists without counting.
INSTALL
composer require crhg/eloquent-exists-relation
This package is compliant with Package Discovery so no additional configuration is required.
In case of Lumen
Register EloquentExistsRelationProvider as follows in bootstrap/app.php.
$app->register(\Crhg\EloquentExistsRelation\Providers\EloquentExistsRelationProvider::class);
USAGE
If you want to know wheather results from a relationship exists without actually loading them you may use the withExists method, which will place a {relation}_exists column on your resulting models. For example:
$posts = App\Post::withExists('comments')->get(); foreach ($posts as $post) { echo $post->comments_exists; }
You may add the "exists" for multiple relations as well as add constraints to the queries:
$posts = App\Post::withCount(['votes', 'comments' => function ($query) { $query->where('content', 'like', 'foo%'); }])->get(); echo $posts[0]->votes_exists; echo $posts[0]->comments_exists;
You may also alias the relationship exists result, allowing multiple exists on the same relationship:
$posts = App\Post::withCount([ 'comments', 'comments as pending_comments_exists' => function ($query) { $query->where('approved', false); } ])->get(); echo $posts[0]->comments_exists; echo $posts[0]->pending_comments_exists;
TIPS
Since the value of EXISTS may not be a boolean value (for example, 0 or 1 in mysql), it is convenient to cast it explicitly when you want to treat it as a boolean value.
protected $cast = [ 'commensts_exists' => 'bool', ];
统计信息
- 总下载量: 138
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 0
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2018-11-21