首页 > 解决方案 > 扩展一个始终将“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 资源。

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

标签: phplaravellaravel-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..
    }

    //
}

推荐阅读