simpladevru / laravel-eloquent-join
本包引入了eloquent模型和关系中的连接魔法。
Requires
- illuminate/database: ^5.5|^6.0|^7.0|^8.0
Requires (Dev)
- dev-master
- 4.1.3
- 4.1.2
- 4.1.1
- 4.1.0
- 4.0.9
- 4.0.8
- 4.0.7
- 4.0.6
- 4.0.5
- 4.0.4
- 4.0.3
- 4.0.2
- 4.0.1
- 4.0.0
- 3.0.2
- 3.0.1
- 3.0.0
- 2.2.4
- 2.1.x-dev
- 2.1.4
- 2.1.3
- 2.1.2
- 2.1.0
- 2.0.x-dev
- 2.0.4
- 2.0.3
- 2.0.2
- 2.0.0
- 1.3.x-dev
- 1.3.4
- 1.3.3
- 1.3.2
- 1.3.0
- 1.2.x-dev
- 1.2.4
- 1.2.3
- 1.2.2
- 1.2.1
- 1.2.0
- dev-filip-patch-5
- dev-filip-patch3
- dev-filip-patch2
- dev-filip-patch
This package is not auto-updated.
Last update: 2024-09-20 01:46:58 UTC
README
Laravel Eloquent Join
本包引入了eloquent模型和关系中的连接魔法。
介绍
Eloquent是一个非常强大的ORM,但其连接能力非常弱。
第一个Eloquent问题(排序)
使用laravel,你无法在不手动连接相关表的情况下对关系字段进行排序,这非常尴尬。让我给你几个原因。如果你有一个包含文章和相关分类的表,你的代码可能看起来像这样
$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('posts.*')
原因:如果没有从分类中选择id,它可以被选中并注入到Post模型中。
2.第二个问题是你需要考虑groupBy。
->groupBy('posts.id');
原因:如果关系是HasOne,并且一篇文章有多个分类,查询将返回更多行的分类。
3.第三个问题是你需要将所有其他where子句从
->where('date', $date)
更改为
->where('posts.date', $date)
原因:一篇文章和分类都可以有“日期”属性,在这种情况下,如果没有选择表中的属性,将会抛出“模糊列”错误。
4.第四个问题是你在使用表名(不是模型),这也很糟糕且尴尬。
->where('posts.date', $date)
5.第五个问题是你需要考虑连接表的软删除。如果分类使用了SoftDeletes特质,你必须添加
->where('categories.deleted_at', '=', null)
这个包将为你处理所有上述问题。与排序不同,你可以在不连接相关表的情况下对关系字段进行过滤,但这个包将为你提供更容易做到这一点的能力。
第二个Eloquent问题(子查询)
使用laravel,你可以对关系属性进行where操作,但laravel会生成比连接更慢的子查询。使用这个包,你将能够以优雅的方式使用连接对关系进行where操作。
要求
本包还对SQLite、MySql和PostgreSql进行了测试
安装与设置
1.使用composer安装包
composer require fico7489/laravel-eloquent-join
使用此语句,composer将安装适用于您当前laravel版本的最新包版本。
2.在您的基模型或特定模型中,使用Fico7489\Laravel\EloquentJoin\Traits\EloquentJoinTrait特质。
...
use Fico7489\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"
...
每个关系都用下划线连接,并在末尾添加_count前缀。例如,对于
->joinRelations('seller.locations')
字段将变成seller_locations_count
leftJoin
是否应该使用inner join或left join(默认为true)
select "sellers".*
from "sellers"
inner join "locations"
...
versus
select "sellers".*
from "sellers"
left join "locations"
...
aggregateMethod
选择用于排序的聚合方法(默认为 'MAX')。
当在连接表上执行连接时,我们必须在排序字段上应用聚合函数,以便我们可以执行分组子句并防止结果重复。
select "sellers".*, MAX("locations" ."number") AS sort
from "sellers"
left join "locations"
group by "locations" ."id"
order by sort
...
选项有:SUM、AVG、MAX、MIN、COUNT
用法
当前可用于连接查询的关系
- BelongsTo
- HasOne
- HasMany
BelongsTo和HasOne关系上eloquent构建器的新子句
joinRelations($relations, $leftJoin = null)
- $relations 要连接的关系
- $leftJoin 使用 左连接 或 内连接,默认 左连接
orderByJoin($column, $direction = 'asc', $aggregateMethod = null)
- $column 和 $direction 参数与默认eloquent的 orderBy() 中的参数相同
- $aggregateMethod 参数定义要使用的聚合方法(SUM、AVG、MAX、MIN、COUNT),默认 MAX
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)
- 参数与默认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')
连接(混合左连接)
卖家::joinRelations('城市', true)->joinRelations('城市.州', false)
连接(多个关系)
卖家::join(['城市.州', '位置'])
排序
按 BelongsTo 排序
卖家::orderByJoin('城市.title')
按 HasOne 排序
卖家::orderByJoin('locationPrimary.address')
按 HasMany 排序
卖家::orderByJoin('locations.title')
混合排序
卖家::orderByJoin('城市.州.title')
排序(具有聚合函数的特殊情况)
按关系数量排序
卖家::orderByJoin('locations.id', 'asc', 'COUNT')
按关系字段 SUM 排序
卖家::orderByJoin('locations.is_primary', 'asc', 'SUM')
按关系字段 AVG 排序
卖家::orderByJoin('locations.is_primary', 'asc', 'AVG')
按关系字段 MAX 排序
卖家::orderByJoin('locations.is_primary', 'asc', 'MAX')
按关系字段 MIN 排序
卖家::orderByJoin('locations.is_primary', 'asc', 'MIN')
过滤(where 或 orWhere)
按 BelongsTo 过滤
卖家::whereJoin('城市.title', '=', 'test')
按 HasOne 过滤
卖家::whereJoin('locationPrimary.address', '=', 'test')
按 HasMany 过滤
卖家::whereJoin('locations.title', '=', 'test')
混合过滤
卖家::whereJoin('城市.州.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"
贡献
请随意为新问题创建问题
- 错误
- 通知
- 请求新功能
- 问题
- 澄清
- 等等...
许可
MIT
自由软件,太棒了!