crhg/eloquent-exists-relation

添加withExits方法,通过子查询检查相关记录的存在性。

v1.1.2 2020-01-22 02:13 UTC

This package is auto-updated.

Last update: 2024-09-22 12:35:07 UTC


README

在Eloquent模型中使用子查询添加一个属性,以指示在获取时是否有关联指定的元素。这与withCount类似,后者查找关系的元素数量,但不同之处在于它仅获取是否存在,而不进行计数。

安装

composer require crhg/eloquent-exists-relation

此包符合包发现规范,因此无需进行额外配置。

对于Lumen

bootstrap/app.php中注册EloquentExistsRelationProvider,如下所示。

$app->register(\Crhg\EloquentExistsRelation\Providers\EloquentExistsRelationProvider::class);

用法

如果您想了解关系的结果是否存在,而不实际加载它们,您可以使用withExists方法,该方法将在您的结果模型上放置一个{relation}_exists列。例如

$posts = App\Post::withExists('comments')->get();

foreach ($posts as $post) {
    echo $post->comments_exists;
}

您可以为多个关系添加“存在”,并为查询添加约束

$posts = App\Post::withCount(['votes', 'comments' => function ($query) {
    $query->where('content', 'like', 'foo%');
}])->get();

echo $posts[0]->votes_exists;
echo $posts[0]->comments_exists;

您还可以将关系存在结果别称化,允许在相同的关系上多次存在

$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;

技巧

由于EXISTS的值可能不是布尔值(例如,MySQL中的0或1),因此当您希望将其视为布尔值时,显式转换它很方便。

    protected $cast = [
        'commensts_exists' => 'bool',
    ];