扩展了一个Laravel模型,该模型始终附加一个“ where status ='cancelled'`来选择语句?

问题描述 投票:0回答:1

我正在使用Laravel和Nova。所以基本上在Laravel中,我有一个像这样的模型:

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

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 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 ...
}

这一切正常,除了现在我想创建两个不同的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'`

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

好奇如何做到这一点?还是有更好的方法实现我的目标?

php laravel laravel-nova
1个回答
0
投票

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

FlightCancelled

protected $table = 'flights'

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

在这种情况下,我建议使用lenses,允许您完全自定义基础资源的高级查询。

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

    //
}
© www.soinside.com 2019 - 2024. All rights reserved.