lorisleiva/laravel-add-select

v0.1.4 2020-10-21 16:50 UTC

This package is auto-updated.

Last update: 2024-08-29 05:24:18 UTC


README

🧱 使用动态方法为Laravel模型添加subSelect查询。

如果你不熟悉subSelect查询,我强烈推荐阅读Johnathan Reinink的这篇文章

安装

composer require lorisleiva/laravel-add-select

用法

考虑两个Eloquent模型BookChapter,一个书可以有多个章节。

使用AddSubSelects特性,现在你可以通过遵循命名约定add{NewColumnName}Select将subSelect查询添加到Book模型中。例如,以下代码为列last_chapter_idlatest_version添加了两个新的subSelect查询。

class Book extends Model
{
    use AddSubSelects;

    public function addLastChapterIdSelect()
    {
        return Chapter::select('id')
            ->whereColumn('book_id', 'books.id')
            ->latest();
    }

    public function addLatestVersionSelect()
    {
        return Chapter::select('version')
            ->whereColumn('book_id', 'books.id')
            ->orderByDesc('version');
    }
}

现在,你可以使用withSelect方法延迟加载这些subSelect查询。

Book::withSelect('last_chapter_id', 'latest_version')->get();

你也可以使用loadSelect方法延迟加载已经存在于内存中的模型。请注意,此方法将一次性加载所有提供的subSelect查询。

$book->loadSelect('last_chapter_id', 'latest_version');

如果你没有在模型中延迟加载这些subSelect查询,你仍然可以将其作为属性访问。第一次访问时,它们将导致新的数据库查询,但随后的访问它们将在模型的属性中可用。

$book->last_chapter_id;
$book->latest_version;

最后,你可以通过在Eloquent模型上设置withSelect属性来全局延迟加载这些subSelect查询。

class Book extends Model
{
    use AddSubSelects;

    public $withSelect = ['last_chapter_id', 'latest_version'];
}