Laravel Eloquent 比较列值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30331437/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 17:01:25  来源:igfitidea点击:

Laravel Eloquent Compare Column Values

laraveleloquent

提问by Jake Opena

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

where()比较两列值时,Eloquent似乎不起作用。如何解决?

Sample code:

示例代码:

->where('table_1.name', '=', 'table_2.name')

But works on:

但适用于:

->where('table_1.name', '=', 'john')

回答by Limon Monte

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

在这种情况下不需要转义,您可以使用whereRaw()

->whereRaw('table_1.name = table_2.name')

回答by Carolyn Lim

You can use where column:

您可以使用 where 列:

->whereColumn('table_1.name', 'table_2.name')

回答by Jake Opena

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

我想到了。'table_2.name'被解释为纯字符串而不是 mysql 表列。

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')
    
  1. 'table_2.name'\DB::raw()

    ->where('table_1.name', '=', \DB::raw('table_2.name'))
    
  2. whereRaw()(基于@limonte 的回答)包裹整个表达式

    ->whereRaw('table_1.name = table_2.name')