msafadi/laravel-eloquent-join-with

Laravel Eloquent 关联查询包

v1.1 2024-05-20 08:19 UTC

This package is auto-updated.

Last update: 2024-09-24 14:41:07 UTC


README

Laravel Eloquent Join With 是一个简化在现有 Eloquent 关联关系(类型为 HasOneBelongsTo)上进行高效数据库连接的包。通过利用这些关系,JoinWith 通过执行单个查询而不是标准 with 方法通常所需的两个单独查询来优化性能。这表示更快、更高效的数据检索。

安装

您可以通过 composer 安装此包

composer require msafadi/laravel-eloquent-join-with

使用方法

您可以在应用程序模型中使用两种方法来使用 Laravel JoinWith

1. 使用 JoinWith 特性

在您的应用程序模型中包含此包提供的 JoinWith 特性

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Safadi\EloquentJoinWith\Database\Concerns\JoinWith;

class User extends Model
{
    use JoinWith;

    // ... other model properties and methods
}

包含特性后,您可以直接在您的模型查询中使用 joinWith 方法。

2. 扩展模型类

或者,您可以通过 Safadi\EloquentJoinWith\Database\Eloquent\Model 扩展您的模型类

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Safadi\EloquentJoinWith\Database\Eloquent\Model as JoinWithModel;

class User extends JoinWithModel
{
    // ... other model properties and methods
}

这种方法也允许您在模型查询中访问 joinWith 方法。

使用示例

一旦您将 Laravel JoinWith 集成到模型中,您就可以在 Eloquent 模型查询中使用 joinWith 方法。

joinWith 的定义和使用方法与使用标准 with 方法完全相同。但它将执行一个查询,连接父模型和关联模型表,而不是通过执行额外的数据库查询来获取相关模型。以下是一个示例

$user = User::joinWith('profile')
            ->select('users.id', 'users.name')
            ->first();

// This will execute a single query joining the users and profiles tables
// based on the defined HasOne relationship between User and Profile models.

此代码通过单个查询检索用户信息和相关配置文件的头像。

与标准 with 方法一样,您也可以使用嵌套关系

$user = User::joinWith('profile.country')
            ->first();

// This will execute a single query joining the users, profiles, and countries tables
// based on the defined HasOne relationship between User and Profile and between Profile and Country models.

对于更复杂的情况,您可以向 joinWith 方法传递一个闭包以自定义连接条件,类似于标准 with 方法

$orders = Orders::joinWith(['user' => function ($query) {
    $query->where('users.status', '=', 'verified');
}])
->get();

// This will execute a single query joining orders and users tables
// based on the BelongsTo relationship and the additional where clause.

此示例检索属于已验证用户的订单,通过单个查询合并用户和订单信息。

限制

  • Laravel JoinWith 目前仅支持 HasOneBelongsTo 关联关系。可能在未来的版本中添加对其他关系类型的支持。
  • 指定要检索的关联关系的哪些列目前尚不支持,但可能在未来的版本中添加。

贡献

我们欢迎对此包的贡献!如果您想贡献,请随时打开一个 pull request。

许可协议

此包采用 MIT 许可证分发。请参阅 LICENSE 文件以获取更多信息。