扩展始终附加"where status ='已取消'"的 Laravel 模型来选择语句?



我正在与Laravel和Nova合作。所以基本上在Laravel,我有一个这样的模型:

<?php
namespace App;
use IlluminateDatabaseEloquentModel;
class Flight extends Model
{
}

然后,Nova帮助我在https://example.com/admin/resouces/flights创建了一个不错的CMS web界面,列出了我的所有航班和https://example.com/admin/resouces/flights/<id>,让我可以根据特定记录进行CRUD。要实现这一点,我所要做的就是创建内容为的文件app/Nova/Flight.php

<?php
namespace AppNova;
//... 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 = 'AppFlight';
// ... list of fields I want to modify ...
}

这一切都很好,除了现在我想制作两个不同的url,比如:

* `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'`

随着项目的发展,事情会变得更加复杂,所以我想知道是否有一种方法可以定义一个名为AppFlightCancelled的新模型,它与AppFlight完全相同,只是对数据库的所有查询都将始终包含WHERE status='cancelled'条件。这样,我就可以将AppFlightCancelled指定为Nova资源的模型。

好奇是怎么做到的?或者是否有更好的方法来实现我的目标?

您可以修改$table并覆盖newQuery()——Eloquent用于构造新查询的方法。

航班取消

protected $table = 'flights'
public function newQuery($excludeDeleted = true)
{
return parent::newQuery($excludeDeleted)
->where('status', '=', 'cancelled');
}

在这种情况下,我建议使用镜头,允许您完全自定义底层资源Eloquent查询。

class FlightCancelled extends Lens
{
public static function query(LensRequest $request, $query)
{
// Query here..
}
//
}

最新更新