【问题标题】:How to filter Records by category in PHP Laravel Twig?如何在 PHP Laravel Twig 中按类别过滤记录?
【发布时间】:2017-06-27 12:05:12
【问题描述】:

我正在使用OctoberCMS 制作一个简单的画廊,基于LaravelTwig

如何按类别过滤记录?

这是我现在的做法,但我认为这不是一个好的解决方案:

我过滤了html,但是分类之外的所有项目的完整记录仍然存在,导致额外的分页和空白页。

数据库

  • 表“画廊”包含类别名称列表。

  • “图像”表包含图像名称及其标记类别。

图片列表

网址参数是/gallery/:category?/:page?

访问像 /gallery/nature/1 这样的网址将使用 for 循环按类别过滤图像。

<!-- Gallery Category Record Variable -->
{% set category = record.category %}

<!-- Image List -->
{% for record in records %}

    <!-- If Image Category Tag matches Gallery Category Name -->
    {% if record.category_tag == category %} 
        <img src="/{{ record.name }}.jpg">
    {% endif %}

{% endfor %}

记录

“记录”和“记录”的结果。

for 循环在 'images→category_tag' 记录中显示 'gallery→category' 记录。

分页显示所有“图像→名称”记录。

{% for record in records %} = (All in 'images')
{{ records }} = {<ul><li>...<a href="gallery/nature?page=2">2</a>} (All in 'images')
{{ record }} = {"category":"nature","id":7} (Current category in 'gallery')

解决方案?

有没有办法在生成 html 列表之前按类别过滤“记录”?

【问题讨论】:

  • 不确定我是否误解了,但是在将符合条件的记录传递给视图之前获取它不是更简单吗?喜欢Gallery::where('category_id', $catId)-&gt;get()。当然,您首先必须使用从参数中获取的名称来获取类别 ID
  • @ChristopherFrancisco 通过OctoberCMS 拖放记录列表或记录详细信息,然后设置模型类和显示列。从那里您可以使用 Twig 语法来使用记录。我是新手,在 Twig 之外使用 Laravel。
  • 我的错,OctoberCMS 的链接重定向到分页页面,所以我认为它只是一个分页组件(尽管名字说 CMS,我傻了哈哈哈)
  • @ChristopherFrancisco 我听取了您的建议并尝试使用 Gallery::select()->where()->paginate();它正在解决一些问题,例如缺少 CurrentPage 值。
  • 最好在你的组件中进行过滤,一个很好的例子是 RainLab 博客插件,看看它是如何按类别过滤帖子的

标签: php laravel twig octobercms


【解决方案1】:

这就是我的处理方式:

  • 在您的图像模型中创建一个按页面、类别等过滤的范围。
  • 在您的组件中处理 URL 属性和逻辑而不是视图

比方说画廊组件:

网址:page.com/:cat/:page?

    public function defineProperties()
    {
        return [
            // Page # for pagination..
            'pageNumber' => [
                'title'       => 'Page #',
                'description' => 'Gallery Page #',
                'type'        => 'string',
                'default'     => '{{ :page }}',
            ],
            // Category slug
            'category' => [
                'title'       => 'Category',
                'description' => 'Gallery Cat',
                'type'        => 'string',
                'default'     => '{{ :cat }}',
            ],
            // Images to show per page
            'perPage' => [
                'title'             => 'Images per page',
                'type'              => 'string',
                'validationPattern' => '^[0-9]+$', //  validation
                'validationMessage' =>  'VValidation Error',
                'default'           => '15', 
            ],
            // if you want to add sorting
            'sortOrder' => [
                'title'       => 'Sort Order',
                'description' => 'Images Sort Order',
                'type'        => 'dropdown',
                'default'     => 'updated_at desc' 
            ],
        ];
    }

public function getSortOrderOptions()
{
    return Image::$allowedSortingOptions;
}


public function init()
{
    $this->pageNumber   =  empty($this->property('pageNumber')) ? 1 :   $this->property('pageNumber');
    $this->perPage      =  $this->property('perPage');
    $this->sortOrder    =  $this->property('sortOrder');
    $this->category     =  $this->property('category');
}

public function onRun()
{

  // here you may want to do some checks 
 // and add logic before querying your DB

    return $this->listImages($this->pageNumber , $this->sortOrder,  $this->perPage, $this->category);

}

public function listImages($pageNumber, $sortOrder, $perPage, $category){

  // this is the scope you will define in your Images Model
 // to handle pagination, sorting, category filtering ect..

    $images = Images::listFrontEnd([
        'page'          => $pageNumber,
        'sort'          => $sortOrder,
        'perPage'       => $perPage,
        'category'      => $category,
    ]);



   // small helper if the pagination # is > than last page
  // redirect to last page..

    $lastPage = $images->lastPage();

    if ($this->pageNumber > $lastPage && $this->pageNumber > 1){
            return Redirect::to($this->currentPageUrl(["page" =>  $lastPage]));
        }


 $this->images  = $this->page['images'] = $images;

}

在您的图像模型中:

// list the allowed sorting options that will show up in your component

public static $allowedSortingOptions = array(
    'created_at asc'            => 'Images Created (ascending)',
    'created_at desc'           => 'Images Created (descending)',
    'updated_at asc'            => 'Images Updated (ascending)',

  //        ect....
);


// Scope for your component
public function scopelistImages($query, $options)
    {
        /*
         * Default options
         */
        extract(array_merge([
            'page'              => 1,
            'perPage'           => 15,
            'sort'              => 'updated_at',
            'category'          => null
        ], $options));



        // SORTING
        if (!is_array($sort)) {
            $sort = [$sort];
        }

        foreach ($sort as $_sort) {

            if (in_array($_sort, array_keys(self::$allowedSortingOptions))) {
                $parts = explode(' ', $_sort);
                if (count($parts) < 2) {
                    array_push($parts, 'desc');
                }
                list($sortField, $sortDirection) = $parts;
                if ($sortField == 'random') {
                    $sortField = Db::raw('RAND()');
                }
                $query->orderBy($sortField, $sortDirection);
            }
        }

        // Filter by category
         ........


        return $query->paginate($perPage, $page);
    }

答案灵感来自RainLab Blog Plugin

【讨论】:

    猜你喜欢
    • 2021-10-26
    • 1970-01-01
    • 2020-10-23
    • 1970-01-01
    • 2021-12-23
    • 2018-12-14
    • 2012-06-12
    • 2017-10-24
    • 2013-05-05
    相关资源
    最近更新 更多