z-song / demo.laravel-admin.org

Source code of official http://demo.laravel-admin.org website.
507 stars 250 forks source link

Filter not working with a join eloquent in grid #24

Closed enaeim closed 6 years ago

enaeim commented 6 years ago

Hi.

Description :

I use a join eloquent in grid and then I use filter method. But the filter doesn't work. I know that in the query below, product_id = 1 is incorrect and branch_product.product_id = 1. But I don't know how to fix it in the filter method.

Error :

QueryException In Connection.php line 664 : SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'product_id' in where clause is ambiguous (SQL: select count(*) as aggregate from branch_product inner join branch_product_stock on branch_product_stock.id = branch_product.id where product_id = 1)

image

Tables :

branch_product table columns: id, branch_id, product_id branch_product_stock table columns: id, stock

Controller :

`class BranchProductController extends Controller {

protected function grid()
{
    return Admin::grid(BranchProduct::class, function (Grid $grid) {

        $grid->model()
            ->join('branch_product_stock', 'branch_product_stock.id', '=', 'branch_product.id')
            ->select('branch_product.*', 'branch_product_stock.stock')
            ->orderBy('branch_product.branch_id')
            ->orderBy('branch_product.id');

        $grid->column('id', 'ID')->sortable();
        $grid->column('product.name', 'product')->sortable();
        $grid->column('branch.name', 'branch')->sortable();
        $grid->column('stock', 'stock')->sortable();

        $grid->filter(function (Grid\Filter $filter) {
            $filter->equal('product_id', 'product')->select(Product::all()->pluck('name', 'id'));
            $filter->equal('branch_id', 'branch')->select(Branch::all()->pluck('name', 'id'));
        });
    });
}

}`

Thans for your help.

enaeim commented 6 years ago

I found the solution myself.

I use the filter method below :

`$grid->filter(function (Grid\Filter $filter) {

    $filter->where(function ($query) {
            $query->where('branch_product.product_id', "{$this->input}");
    }, 'product')->select(Product::all()->pluck('name', 'id'));
    $filter->where(function ($query) {
            $query->where('branch_product.branch_id', "{$this->input}");
    }, 'branch')->select(Branch::all()->pluck('name', 'id'));

});`

best regards

by-plugin commented 4 years ago
$filter->where(function ($query) {
            $query->whereHas('branch_product',  function($query){
                   $query->where('product_id', $this->input);
            });
    }, 'product')->select(Product::all()->pluck('name', 'id'));

work for me