vendredi 26 février 2016

How to search by columns union in datatable?

i need to search by user firstname and lastname where are merge to one. Im working with laravel 5.1 and http://ift.tt/1QjEdLi.

Here is me code of backend query:

                $orders = Order::select([
                                    'orders.created_at',
                                    'users.firstname AS user_firstname',
                                    'users.lastname AS user_lastname'
                            ])
                            ->join('users', 'users.id', '=', 'orders.user_id')
                            ->where('orders.client_id', \Auth::user()->client_id)
                            ->where('orders.status', 'finished');

And return:

        return Datatables::of($orders)
                    ->addColumn('user', function ($user) {
                        return $user->user_firstname.' '.$user->auser_lastname;
                    })
                    ->addColumn('action', function ($order) {
                        return '<div class="btn-group" style="min-width: 76px;">
                                    <a href="'.url('history/order/edit/'.$order->id).'" class="btn btn-default"><i class="fa fa-edit"></i></a>
                                    <a href="'.url('history/order/delete/'.$order->id).'" class="btn btn-default" onClick="return confirm(\'Are you sure?\');"><i class="fa fa-times"></i></a>
                                </div>';
                    })
                    ->removeColumn('user_firstname')
                    ->removeColumn('user_lastname')
                    ->make(true);

I merge user column to one with user_firstname and user_lastname.

When im searchng in datatable i need to search by this column - USER. Query to to be like this:

SELECT
    `orders`.`created_at`,
    `users`.`firstname` AS `agent_firstname`,
    `users`.`lastname` AS `agent_lastname`,
FROM
    `orders`
INNER JOIN `users` ON `users`.`id` = `orders`.`user_id`
WHERE
    `orders`.`client_id` = '3'
AND `orders`.`status` = 'finished'
AND (
    LOWER(`orders`.`created_at`) LIKE '%search_word%'
    OR LOWER(`users`.`firstname`) LIKE '%search_word%'
    OR LOWER(`users`.`lastname`) LIKE '%search_word%'
)
ORDER BY
    `orders`.`created_at` DESC
LIMIT 10 OFFSET 0

Here is my datatable JS:

// Data tables
var oTable = $('#orders-data').dataTable({
    "processing": true,
    "serverSide": true,
    "ajax": '/history/orders',
    "columns": [
        { data: 'created_at', name: 'orders.created_at' },
        { data: 'user', name: 'user' },
        { data: 'action', name: 'action', orderable: false, searchable: false }
    ],
});

If I change line { data: 'user', name: 'user' } in JS to { data: 'user', name: 'users.firstaname' } than searching only in users.firstname column, But i need search in users.lastname too.

How to do that?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire