繁体   English   中英

在 Laravel Nova 中为不同的资源使用一张表

[英]Use one table for different resource in Laravel Nova

我正在尝试在 Laravel Nova 中创建类似博客系统的东西。

我有一个名为articles的表以及抽象模型AbstractArctile
我也有3类:

  • 新闻 - App\Models\News\Article扩展了App\Models\Abstract\AbstractArticle
  • 摘要 - App\Models\Digests\Article扩展了App\Models\Abstract\AbstractArticle
  • Offtopic - App\Models\Offtopic\Article扩展App\Models\Abstract\AbstractArticle

表中的articles有一个名为category的字段,类别有 3 种类型: news、digests、offtopic

每个资源模型除了扩展抽象模型外,还定义了一个属性,即它的类别,具体方式如下:

/**
 * To which category this article belongs to
 * @var array
 */
protected $attributes = [
    'category'  =>  'news'
];

我在 Nova 中创建指定类别下的文章没有问题,但是,它不是显示指定类别的文章,而是显示所有资源上所有类别的文章。

有没有办法只显示给定资源上某个类别的文章?

概括

一个抽象模型-> 3 个扩展该模型的资源(定义了类别属性)-> 如何在 nova 资源中仅显示该类别中的项目?

您可以利用 Laravel 雄辩的查询范围

为所有 3 个模型( App\Models\News\ArticleApp\Models\Digests\ArticleApp\Models\Offtopic\Article )添加如下全局范围,这是确保给定模型的每个查询都接收到的简单方法类别约束。

protected static function boot()
{
    parent::boot();

    static::addGlobalScope('category', function (Builder $builder) {
        $builder->where('category', 'news'); // Change the value depends on the model
    });
}

希望这会帮助你。

在 Nova 中,您也可以使用 indexQuery、detailQuery 和 editQuery 并自定义您的资源结果。

https://nova.laravel.com/docs/4.0/resources/authorization.html#index-filtering

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM