Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

To be able to filter/search by foreign table's field #36

Open
bilogic opened this issue Apr 5, 2021 · 1 comment
Open

To be able to filter/search by foreign table's field #36

bilogic opened this issue Apr 5, 2021 · 1 comment

Comments

@bilogic
Copy link
Contributor

bilogic commented Apr 5, 2021

Hi,

I would like to propose being able to write code like below:

TD::make('payment_gateway_id', 'Payment Gateway')
    ->sort()
    ->query(function ($search, $builder) {
        return $builder
            ->select('customers.*') // required, otherwise sorting has issues
            ->join('payment_gateways', 'payment_gateways.id', '=', 'payment_gateway_id')
            ->where('payment_gateways.name', 'like', '%' . $search. '%');
    })
    ->render(function ($model) {
        return $model->payment_gateway->name;
    })

The purpose is so that we can search for a foreign table's field e.g. name instead of only being able to filter by ID as the user might not know the ID.

I was able to modify ResourceRequest.php with the code below,

    // update in ResourceRequest.php
    public function getModelPaginationList()
    {
        $builder = $this->model()
            ->with($this->resource()->with())
            ->filters()
            ->filtersApply($this->resource()->filters());

        foreach (collect($this->resource()->columns()) as $column) {
            $callback = $column->queryClosure; // also need to modify TD.php to support queryClosure
            if (!is_null($callback)) {
                $filters = $this->request->all('filter');
                $key = $column->column;
                if (Arr::exists($filters, $key)) {
                    $term = $filters[$key];
                    $builder = $callback($term, $builder);
                }
            }
        }

        return $builder->paginate($this->resource()->perPage());
    }

    // add to TD.php
    /**
     * @var Closure|null
     */
    public $queryClosure;

    public function query(Closure $queryClosure)
    {
        $this->queryClosure = $queryClosure;
        return $this;
    }

Is there a better approach to make searching by foreign table field easier?

@bilogic
Copy link
Contributor Author

bilogic commented Apr 7, 2021

@tabuna able to let me know? My code is starting to rely on this and I would like such functionality to be in the main crud repo. Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

1 participant