php - 扩展一个始终将“where status = 'cancelled'”附加到选择语句的 Laravel 模型?
问题描述
我正在与 Laravel 和Nova合作。所以基本上在 Laravel 中,我有一个这样的模型:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Flight extends Model
{
}
然后,Nova 帮助我创建了一个漂亮的 CMS Web 界面,https://example.com/admin/resouces/flights
其中列出了我所有的航班,并https://example.com/admin/resouces/flights/<id>
让我对特定记录进行 CRUD。我要做的就是创建app/Nova/Flight.php
包含以下内容的文件:
<?php
namespace App\Nova;
//... import other classes like Text Fields, WYSIWYG editors etc.. etc.., that are the nice CMS UI fields to modify each column in my flights table
class Flight extends Resource
{
public static $model = 'App\Flight';
// ... list of fields I want to modify ...
}
这一切正常,除了现在我想制作两个不同的网址,例如:
* `https://example.com/admin/resouces/flights-cancelled` - this should only list the equivalent of `SELECT * FROM flights WHERE status = 'cancelled'`
* `https://example.com/admin/resouces/flights-active` - this should only list the equivalent of `SELECT * FROM flights WHERE status = 'active'`
随着我的项目的发展,事情会变得有点复杂,所以我想知道是否有一种方法可以定义一个App\FlightCancelled
与 完全相同的新模型App\Flight
,除了对数据库的所有查询都将始终包含一个WHERE status='cancelled'
条件。这样我就可以将App\FlightCancelled
模型分配给我的 Nova 资源。
好奇这是怎么做到的?或者是否有更好的方法来实现我的目标?
解决方案
您可以修改$table
和覆盖newQuery()
- Eloquent 用来构造新查询的方法。
航班取消
protected $table = 'flights'
public function newQuery($excludeDeleted = true)
{
return parent::newQuery($excludeDeleted)
->where('status', '=', 'cancelled');
}
在这种情况下,我推荐使用lens,让您完全自定义底层资源 Eloquent 查询。
class FlightCancelled extends Lens
{
public static function query(LensRequest $request, $query)
{
// Query here..
}
//
}
推荐阅读
- .net-core - 如何使用自定义策略模式实现 jwt 令牌基础身份验证以在 .net 核心中进行授权?
- powershell - Powershell - 设置参数可选并让其他参数位于其位置(0)
- android - “ScreenSlidePagerAdapter 扩展 FragmentStateAdapter”类中的片段位置中的 ViewPager 2 位置错误
- c++ - 为什么对象不会使用 new 初始化?
- python - 可视化 RGB 图像的不同颜色通道的问题
- python - 如何将数据分成两个数据框
- python - 使用 Python 进行单词预测
- arrays - 在 MIPS 中,如何显示主要方法的结果?
- java - 版本 32 位还是 64 位?如何检查
- django - 使用 StatReloader 监视文件更改