Laravel Eloquent Compare Column Values

前端 未结 3 1083
耶瑟儿~
耶瑟儿~ 2020-12-16 09:41

Eloquent\'s where() seems not working when comparing two column values. How to fix it?

Sample code:

->where(\'table_1.name\', \'=\',          


        
相关标签:
3条回答
  • 2020-12-16 10:27

    Escaping is unnecessary in this case, you can use whereRaw():

    ->whereRaw('table_1.name = table_2.name')
    
    0 讨论(0)
  • 2020-12-16 10:32

    I figured it out. 'table_2.name' is interpreted as plain string and not a mysql table column.

    Possible solutions:

    1. Wrap 'table_2.name'with \DB::raw()

      ->where('table_1.name', '=', \DB::raw('table_2.name'))
      
    2. Wrap the entire expression with whereRaw() (based on @limonte's answer)

      ->whereRaw('table_1.name = table_2.name')
      
    0 讨论(0)
  • 2020-12-16 10:43

    You can use where column:

    ->whereColumn('table_1.name', 'table_2.name')
    
    0 讨论(0)
提交回复
热议问题