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

[Bug] Error when searching self join relationships. #880

Open
coolflames opened this issue Dec 8, 2016 · 10 comments
Open

[Bug] Error when searching self join relationships. #880

coolflames opened this issue Dec 8, 2016 · 10 comments

Comments

@coolflames
Copy link

Summary of problem or feature request

I have a problem when search data

Code snippet of problem

My Model

class Appl_menu extends Model
{
    protected $table = 'appl_menus';
    public $timestamps = false;

    protected $fillable = ['menu_id', 'menu_name', 'menu_module_id', 'menu_file_name', 'menu_id_parent',
        'menu_seqn', 'menu_enable_sts', 'created_by', 'created_date', 'updated_by', 'updated_date'];

    protected $primaryKey = 'menu_id';

    public function nullRelation()
    {
        return null;
    }

    public function menus ()
    {
        return $this->belongsTo(Appl_menu::class,'menu_id_parent');
    }

    public function menuss ()
    {
        return $this->hasMany(Appl_menu::class,'menu_id_parent','menu_id');
    }
}

my controller

public function index(Request $request, Builder $htmlBuilder)
    {
        if ($request->ajax()){
            $menuss = Appl_menu::with('modules', 'menus');
            //->orderBy('module_id');
            return Datatables::of($menuss)
                ->addColumn('action', function ($menu) {
                    return view('datatable._action', [
                        'model' => $menu,
                        'form_url' => route('menus.destroy', $menu->menu_id),
                        'edit_url' => route('menus.edit', $menu->menu_id),
                        'confirm_message' => 'Yakin mau menghapus menu ' . $menu->menu_name . '?'
                    ]);
                })->make(true);
        }

        $html = $htmlBuilder
            ->addColumn(['data' => 'menu_id', 'name' => 'menu_id', 'title' => 'ID'])
            ->addColumn(['data' => 'menu_name', 'name' => 'menu_name', 'title' => 'Nama Menu'])
            ->addColumn(['data' => 'modules.module_name', 'name' => 'modules.module_name', 'title' => 'Module'])
            ->addColumn(['data' => 'menus.menu_name', 'name' => 'menus.menu_name', 'title' => 'Parent', 'defaultContent' => ''])
            ->addColumn(['data' => 'action', 'name' => 'action', 'title' => '', 'orderable' => false, 'searchable' => false]);

        return view('menus.index')->with(compact('html'));
    }

Error output when search

SQLSTATE[42601]: Syntax error: 7 ERROR: syntax error at or near "as"
LINE 1: ...ST("appl_menus" as "laravel_reserved_0.menu_name" as TEXT)) ...
^ (SQL: select count(*) as aggregate from (select '1' as "row_count" from "appl_menus" where (LOWER(CAST("appl_menus"."menu_id" as TEXT)) LIKE %se% or LOWER(CAST("appl_menus"."menu_name" as TEXT)) LIKE %se% or (select count(1) from "appl_modules" where "appl_menus"."menu_module_id" = "appl_modules"."module_id" and LOWER(CAST("appl_modules"."module_name" as TEXT)) LIKE %se%) >= 1 or (select count(1) from "appl_menus" as "laravel_reserved_0" where "laravel_reserved_0"."menu_id" = "appl_menus"."menu_id_parent" and LOWER(CAST("appl_menus" as "laravel_reserved_0.menu_name" as TEXT)) LIKE %se%) >= 1)) count_row_table)

javascript output

<script type="text/javascript">(function(window,$){window.LaravelDataTables=window.LaravelDataTables||{};window.LaravelDataTables["dataTableBuilder"]=$("#dataTableBuilder").DataTable({"serverSide":true,"processing":true,"ajax":"","columns":[{"data":"menu_id","name":"menu_id","title":"ID","orderable":true,"searchable":true},{"data":"menu_name","name":"menu_name","title":"Nama Menu","orderable":true,"searchable":true},{"data":"modules.module_name","name":"modules.module_name","title":"Module","orderable":true,"searchable":true},{"data":"menus.menu_name","name":"menus.menu_name","title":"Parent","defaultContent":"","orderable":true,"searchable":true},{"data":"action","name":"action","title":"","orderable":false,"searchable":false}]});})(window,jQuery);
</script>

What is this error and why that is occurred?

System details

  • Operating System windows10
  • PHP Version 5.6.25
  • Laravel Version 5.2
  • Laravel-Datatables Version 6.22
@yajra
Copy link
Owner

yajra commented Dec 8, 2016

@coolflames can you try returning the query if it works? I think I've seen this issue before and this might be related to self join handling of the DB driver.

return $menuss = Appl_menu::with('modules', 'menus')->get();

If this works, then there must be a bug in the package when compiling self join tables. Thanks for reporting.

@coolflames
Copy link
Author

the query work well the first time populate data, problems appear when it starts input search

@yajra yajra changed the title datatable error when search Error when searching self join relationships. Dec 8, 2016
@yajra yajra changed the title Error when searching self join relationships. [Bug] Error when searching self join relationships. Dec 22, 2016
@lk77
Copy link
Contributor

lk77 commented Feb 13, 2017

Hello,

i think i have the same issue on a n.n relation.

i have a count columns that works on init but when searching the query string is interpreted as a column name in the like clause, and it end up with a sql error.

I don't want that column to be searchable anyway, the searchable parameter is false when i'm doing a dump of $request->query. I don't understand why searchableColumnIndex() still return that column.

i'm on 6.24.4, do i need to update laravel to 5.4 and datatables to 7.*?

thanks

@tad3j
Copy link

tad3j commented Jul 14, 2017

I have another example of failing self joins, where email is having recovery email (one to many) and forwarding to emails (many to many).

Here are the relevant parts of the Email model (relations):

    public function recoveryEmail()
    {
        return $this->belongsTo(EmailAccount::class);
    }

    public function forwardingToEmailAccounts()
    {
        return $this->belongsToMany(
            EmailAccount::class,
            'emails_have_forwarding_emails',
            'forwarding_to_email_id',
            'forwarded_from_email_id'
        );
    }

Here is the failing query, where recoveryEmail is referencing email_accounts table and I'm querying base table with the same name:

EmailAccount::select('email_accounts.*')
    ->with(['recoveryEmail' => function ($query) {
        $query->select(['id', 'email']);
    }]);

And the exception + failing MySQL query:

Exception Message:??SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'email_accounts' (SQL: 
select `email_accounts`.* 
from `email_accounts` 
left join `email_accounts` on `email_accounts`.`recovery_email_id` = `email_accounts`.`id` 
order by `email_accounts`.`email` desc limit 10 offset 0
)

The problem is similar with forwardingToEmails.

I guess this is more of a problem with Eloquent not allowing aliasing, that's why DataTables package doesn't know how to order the data (since both tables -base and joined use the same name).

Was wondering if there may be a workaround for it?

@yajra
Copy link
Owner

yajra commented Apr 24, 2019

Fixed via #2051.

@yajra yajra closed this as completed Apr 24, 2019
@dhcmega
Copy link

dhcmega commented Aug 28, 2019

Hi, I'm using v9.4.1 but still getting the unique table error on self joining for parent relation.
Should I have to modify my code?

My datatables index method and the relation:

    public function query(Topic $model)
    {
        $model = $model->newQuery();

        $model->with('parent')->select('topics.*');

        return $model;
    }

    public function parent()
    {
        return $this->belongsTo('App\Models\Topic', 'parent_id');
    }

Thanks!

@yajra
Copy link
Owner

yajra commented Aug 29, 2019

@dhcmega the PR was reverted as it causes another issue. Self join is currently not yet supported again. Thanks!

@yajra yajra reopened this Aug 29, 2019
@rezasaberi
Copy link

So any suggestion on this yet? I do not even have a self-joined table, but I have same issue.

@hooman-mirghasemi
Copy link

So do you have any plan for fix this problem?

@dens4t
Copy link

dens4t commented Jul 19, 2023

Any fix for this?

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

No branches or pull requests

8 participants