unisharp / laravel-eloquent-join
此包引入了 eloquent 模型和关系的连接魔法。
Requires
- illuminate/database: >=5.8.0
Requires (Dev)
README
此包引入了 eloquent 模型和关系的连接魔法。
介绍
Eloquent 是一个强大的 ORM,但其连接功能非常有限。
第一个 Eloquent 问题(排序)
使用 Laravel,您无法在没有手动连接相关表的情况下对关系字段进行排序,这非常不自然。让我给你几个原因。如果您有一个包含 posts 和相关 categories 的表,您的代码可能看起来像这样
$posts = Post::select('posts.*')
->join('categories', 'categories.id', '=', 'posts.category_id')
->groupBy('posts.id')
->where('categories.deleted_at', '=', null)
->orderBy('categories.name');
if(request()->get('date')){
$posts->where('posts.date', $date)
}
$posts = $posts->get();
1. 第一个问题是你需要担心 select。
->select('posts.*')
原因:没有从 category 中选择 id,它可能会被选中并注入到 Post 模型中。
2. 第二个问题是你需要担心 groupBy。
->groupBy('posts.id');
原因:如果关系是 HasOne,并且对于文章有多个类别,查询将返回更多行。
3. 第三个问题是你需要将所有其他 where 子句从
->where('date', $date)
改为
->where('posts.date', $date)
原因:文章和类别可以有 "date" 属性,在这种情况下,如果没有选择带有表 "ambiguous column" 错误将被抛出。
4. 第四个问题是您正在使用表名(而不是模型),这也是不好的和不自然的。
->where('posts.date', $date)
5. 第五个问题是您需要担心连接表的软删除。如果 category 使用了 SoftDeletes trait,您必须添加
->where('categories.deleted_at', '=', null)
此包将为您处理上述所有问题。与排序不同,您可以在不连接相关表的情况下对关系字段进行 过滤,但此包将使您能够更容易地这样做。
第二个 Eloquent 问题(子查询)
使用 Laravel,您可以在关系属性上执行 where 操作,但 Laravel 会生成比连接更慢的子查询。使用此包,您将以优雅的方式执行关系上的 where 操作。
要求
此包还针对 SQLite、MySql 和 PostgreSql 进行了测试
安装和设置
1. 使用 composer 安装包
composer require fico7489/laravel-eloquent-join
使用此语句,composer 将为您当前 Laravel 版本安装最高版本的包。
2. 在您的基模型或特定模型中使用 UniSharp\Laravel\EloquentJoin\Traits\EloquentJoinTrait 特性。
...
use UniSharp\Laravel\EloquentJoin\Traits\EloquentJoin;
use Illuminate\Database\Eloquent\Model;
abstract class BaseModel extends Model
{
use EloquentJoin;
...
3. 重要
对于 MySql,请确保 strict 配置设置为 false
config/database.php
'mysql' => [
...
'strict' => false,
...
然后您就可以开始了。
选项
可以在模型中设置选项
class Seller extends BaseModel
{
protected $useTableAlias = false;
protected $appendRelationsCount = false;
protected $leftJoin = false;
protected $aggregateMethod = 'MAX';
或是在查询中设置
Order::setUseTableAlias(true)->get();
Order::setAppendRelationsCount(true)->get();
Order::setLeftJoin(true)->get();
Order::setAggregateMethod(true)->get();
useTableAlias
我们是否应该为连接的表使用别名(默认 = false)
使用 true,查询将看起来像这样
select "sellers".* from "sellers"
left join "locations" as "5b5c093d2e00f"
...
使用 false,查询将看起来像这样
select "sellers".*
from "sellers"
left join "locations"
...
别名是随机生成的字符串。
appendRelationsCount
我们是否应该自动将关系计数字段附加到结果中(默认 = false)
使用 true,查询将看起来像这样
select "sellers".*, count(locations.id) AS locations_count
from "sellers"
left join "locations" as "5b5c093d2e00f"
...
每个 relation 都通过下划线连接,并在末尾添加 _count 前缀。例如,对于
->joinRelations('seller.locations')
字段将变成 seller_locations_count
leftJoin
我们应该使用 inner join 还是 left join(默认 = true)
select "sellers".*
from "sellers"
inner join "locations"
...
vs
select "sellers".*
from "sellers"
left join "locations"
...
aggregateMethod
用于排序的聚合方法(默认 = 'MAX')。
当在连接的表上执行连接时,我们必须对排序字段应用聚合函数,以便我们可以执行 group by 子句并防止结果重复。
select "sellers".*, MAX("locations" ."number") AS sort
from "sellers"
left join "locations"
group by "locations" ."id"
order by sort
...
选项包括: 求和,平均值,最大值,最小值,计数
用法
当前可用的连接查询关系
- 属于
- 有一个
- 有多个
BelongsTo 和 HasOne 关系上的 eloquent 构建器的新的子句
joinRelations($relations, $leftJoin = null)
- $relations 要连接的关系
- $leftJoin 使用 左连接 或 内连接,默认 左连接
orderByJoin($column, $direction = 'asc', $aggregateMethod = null)
- $column 和 $direction 参数与默认 eloquent orderBy() 中的参数相同
- $aggregateMethod 参数定义要使用的聚合方法(求和,平均值,最大值,最小值,计数),默认 最大值
whereJoin($column, $operator, $value, $boolean = 'and')
- 参数与默认 eloquent where() 中的参数相同
orWhereJoin($column, $operator, $value)
- 参数与默认 eloquent orWhere() 中的参数相同
whereInJoin($column, $values, $boolean = 'and', $not = false)
- 参数与默认 eloquent whereIn() 中的参数相同
whereNotInJoin($column, $values, $boolean = 'and')
- 参数与默认 eloquent whereNotIn() 中的参数相同
orWhereInJoin($column, $values)
- 参数与默认 eloquent orWhereIn() 中的参数相同
orWhereNotInJoin($column, $values, $boolean = 'and')
- 参数与默认 eloquent orWhereNotIn() 中的参数相同
可以在 BelongsTo、HasOne 和 HasMany 关系上使用连接子句的允许子句
- 您想要用于连接查询的关系只能有这些子句:where、orWhere、withTrashed、onlyTrashed、withoutTrashed。
- 子句 where 和 orWhere 只能有以下变体 ** ->where($column, $operator, $value) ** ->where([$column => $value])
- 不允许使用闭包。
- 不允许使用其他子句,如 whereHas、orderBy 等。
- 您可以在关系上添加不允许的子句并按正常 eloquent 方式使用它们,但在这类情况下,您不能使用这些关系进行连接查询。
允许的关系
public function locationPrimary()
{
return $this->hasOne(Location::class)
->where('is_primary', '=', 1)
->orWhere('is_primary', '=', 1)
->withTrashed();
}
不允许的关系
public function locationPrimary()
{
return $this->hasOne(Location::class)
->where('is_primary', '=', 1)
->orWhere('is_primary', '=', 1)
->withTrashed()
->whereHas('state', function($query){return $query;}
->orderBy('name')
->where(function($query){
return $query->where('is_primary', '=', 1);
});
}
第二个关系不允许的原因是,这个包应该将所有这些子句应用于连接子句,而 eloquent 使用所有这些子句独立于子查询 NOT 在连接子句上,这更简单。
您可能觉得规则和限制太多,但事实并非如此。不用担心,如果您创建了不允许的查询,将抛出适当的异常,您将知道发生了什么。
其他
- 如果模型使用了 SoftDelete 特性,则会自动应用 where deleted_at != null
- 您可以无限次地组合新的子句
- 如果您在相同的关系上多次组合子句,则包将只连接相关表一次
Seller::whereJoin('city.title', '=', 'test')
->orWhereJoin('city.title', '=', 'test2');
- 您可以在闭包内部调用新子句
Seller::where(function ($query) {
$query
->whereJoin('city.title', '=', 'test')
->orWhereJoin('city.title', '=', 'test2');
});
- 您可以将连接子句(例如 whereJoin())与 eloquent 子句(例如 orderBy())结合使用
Seller::whereJoin('title', '=', 'test')
->whereJoin('city.title', '=', 'test')
->orderByJoin('city.title')
->get();
参见真实示例上的操作
数据库模式
模型
class Seller extends BaseModel
{
public function locations()
{
return $this->hasMany(Location::class);
}
public function locationPrimary()
{
return $this->hasOne(Location::class)
->where('is_primary', '=', 1);
}
public function city()
{
return $this->belongsTo(City::class);
}
class Location extends BaseModel
{
public function locationAddressPrimary()
{
return $this->hasOne(LocationAddress::class)
->where('is_primary', '=', 1);
}
class City extends BaseModel
{
public function state()
{
return $this->belongsTo(State::class);
}
}
连接
连接 BelongsTo
Seller::joinRelations('city')
连接 HasOne
Seller::joinRelations('locationPrimary')
连接 HasMany
Seller::joinRelations('locations')
混合连接
Seller::joinRelations('city.state')
混合连接(混合左连接)
Seller::joinRelations('city', true)->joinRelations('city.state', false)
排序
排序 BelongsTo
Seller::orderByJoin('city.title')
排序 HasOne
Seller::orderByJoin('locationPrimary.address')
排序 HasMany
Seller::orderByJoin('locations.title')
排序 混合
Seller::orderByJoin('city.state.title')
排序(具有聚合函数的特殊情况)
按关系计数排序
Seller::orderByJoin('locations.id', 'asc', 'COUNT')
按关系字段 SUM 排序
Seller::orderByJoin('locations.is_primary', 'asc', 'SUM')
按关系字段AVG排序
Seller::orderByJoin('locations.is_primary', 'asc', 'AVG')
按关系字段MAX排序
Seller::orderByJoin('locations.is_primary', 'asc', 'MAX')
按关系字段MIN排序
Seller::orderByJoin('locations.is_primary', 'asc', 'MIN')
过滤(where或orWhere)
过滤BelongsTo
Seller::whereJoin('city.title', '=', 'test')
过滤HasOne
Seller::whereJoin('locationPrimary.address', '=', 'test')
过滤HasMany
Seller::whereJoin('locations.title', '=', 'test')
过滤混合
Seller::whereJoin('city.state.title', '=', 'test')
关系计数
$sellers = Seller::setAppendRelationsCount(true)->join('locations', '=', 'test')
->get();
foreach ($sellers as $seller){
echo 'Number of location = ' . $seller->locations_count;
}
过滤(混合左连接)
Seller::joinRelations('city', true)
->joinRelations('city.state', false)
->whereJoin('city.id', '=', 1)
->orWhereJoin('city.state.id', '=', 1)
生成的查询
查询
Order::whereJoin('seller.id', '=', 1)->get();
Sql
select "orders".*
from "orders"
left join "sellers" on "sellers"."id" = "orders"."seller_id"
where "sellers"."id" = ?
and "orders"."deleted_at" is null
group by "orders"."id"
查询
Order::orderByJoin('seller.id', '=', 1)->get();
Sql
select "orders".*, MAX(sellers.id) as sort
from "orders"
left join "sellers" on "sellers"."id" = "orders"."seller_id"
where "orders"."deleted_at" is null
group by "orders"."id"
order by sort asc
包的优雅性
让我们看看文档中的第一个例子现在看起来是什么样子。这段代码
$posts = Post::select('posts.*')
->join('categories', 'categories.id', '=', 'posts.category_id')
->groupBy('posts.id')
->where('categories.deleted_at', '=', null)
->orderBy('categories.name');
if(request()->get('date')){
$posts->where('date', $date)
}
$posts = $posts->get();
现在是
$posts = Post::orderByJoin('category.name');
if(request()->get('date')){
$posts->where('posts.date', $date)
}
$posts = $posts->get();
这两个片段执行相同的功能。
测试
这个包有很好的测试覆盖率。如果你想运行测试,只需运行composer update
,然后使用"vendor/bin/phpunit"
运行测试。
贡献
请随意创建新的问题,例如
- bug
- notice
- 请求新功能
- 问题
- 澄清
- 等等...
许可证
MIT
自由软件,太棒了!