【问题标题】:passing two value for QueryString in livewire在 livewire 中为 QueryString 传递两个值
【发布时间】:2021-10-30 05:55:38
【问题描述】:

我使用 Livewire 并为表格放置一个过滤器。 我的组件有以下代码:

    use WithPagination;
    public bool $loadData = false;
    public $filter_type = null;
    protected $queryString = ['filter_type'];
    

    public function setType($type)
    {
        $this->filter_status = $type;
    }
    
    public function render()
    {
            $transactions = Transaction::when($this->filter_type, function ($query){
                    $query->where('type' , $this->filter_type);
                })
                ->orderBy('created_at', 'DESC')
                ->get();
          return view('livewire.backend.financial.transactions')->with('transactions' , collect($transactions)->paginate(10));
    }

当我应用过滤器时。网址如下

https://example.com/table?filter_type=0

现在我想给filter_type‍‍两个值(例如0和1) 也就是说,显示类型为 0 和 1 的项目。 我该怎么做?

【问题讨论】:

  • 我认为您还有另一个问题:您在 setType 函数中设置的字段与您在查询字符串中使用的字段不同。

标签: laravel laravel-livewire


【解决方案1】:

您可能需要满足一些场景。

1.单值

?filter_type=1

只返回type 等于1 的记录。 filter_type 的值将是一个字符串 "1"

2。多个值(或)

?filter_type=1,2

返回type 等于12 的所有记录。 filter_type 的值将是一个字符串 "1,2"。您可以通过逗号分割字符串以获得实际所需的值。

$values = explode(',', $filter_type);

3.多个值(和)

?filter_type[]=1&filter_type[]=2

返回type12 的所有记录(在这种情况下没有意义,但你明白了)。 filter_type 的值将是一个数组 [0 => 1, 1 => 2]

以上只是建议,但我们假设您选择option 2。您可以按照以下方式实现它;

public function render()
{
    $types = explode(',', $this->filter_type);

    $transactions = Transaction::when($this->filter_type, function ($query) use ($types) {
        $query->whereIn('type', $types);
    })
    ->orderBy('created_at', 'DESC')
    ->get();

    // do what you want with the $transactions
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-02
    • 2021-06-08
    • 1970-01-01
    相关资源
    最近更新 更多