rackbeat / laravel-morph-where-has
修复 morphTo 关系中的 whereHas。
2.0
2022-11-26 08:47 UTC
Requires
- php: >=7.1
- illuminate/contracts: ^6.0|^7.0|^8.0|^9.0
- illuminate/database: ^6.0|^7.0|^8.0|^9.0
- illuminate/support: ^6.0|^7.0|^8.0|^9.0
Requires (Dev)
- phpunit/phpunit: ^7.0
- satooshi/php-coveralls: ^1.0
README
通常情况下,如果 contact 是 morphTo 关系,你不能使用 whereHas('contact')
。此包旨在修复此问题。
安装
您只需使用 composer 就可以了!
composer require rackbeat/laravel-morph-where-has
服务提供器会自动注册。
用法
1. 在您的模型中添加可能的变体
问题在于,形态关系可能很难确定如何处理 whereHas
调用。
我们的解决方案是,您定义每个可能的形态类。例如
<?php class Invoice extends Model { // Old morph relation public function owner() { return $this->morphTo('owner'); } // New solution public function customer() { return $this->morphTo('owner')->forClass(App\Customer::class); } public function supplier() { return $this->morphTo('owner')->forClass(App\Supplier::class); } }
2. 使用 whereHas
Invoice::whereHas('supplier', function($query) { $query->whereName('John Doe'); })->get();
这将正确查询具有类型和您添加的任何查询的关系。
要求
- PHP >= 7.1
灵感
基于 github@thisdotvoid 的作品,修改以解决一些常见问题。