laravel 在laravel查询构建器中选择具有2列相等值的行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25952581/
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-14 10:08:13  来源:igfitidea点击:

Select rows having 2 columns equal value in laravel Query builder

laravel

提问by MrezaJafari

I want to write a query which selects rows where 2 attributes from 1 entity have equal value.

我想编写一个查询来选择来自 1 个实体的 2 个属性具有相等值的行。

This would be an example of doing this in raw SQL:

这将是在原始 SQL 中执行此操作的示例:

Select * from users u where u.username = u.lastname

Does laravel have any methods that take 2 column names as parameters and return the matching results?

Laravel 是否有任何以 2 个列名作为参数并返回匹配结果的方法?

回答by Sergiu Paraschiv

What you need is a DB::rawexpression:

你需要的是一个DB::raw表达式:

DB::table('users')
    ->where('username', '=', DB::raw('lastname'))
    ->get();

The only thing DB::rawactually does is to tell the query interpreter notto treat 'lastname'like any other string value but just interpolateit in the SQL as it is.

DB::raw实际上唯一要做的就是告诉查询解释器不要'lastname'像对待任何其他字符串值一样对待它,而只是将它按原样插入到 SQL 中。

http://laravel.com/docs/queries#raw-expressions

http://laravel.com/docs/queries#raw-expressions

回答by ceejayoz

In Laravel 5, there's nowwhereColumnfor this, for cleaner code:

在 Laravel 5 中,现在有了whereColumn更清晰的代码:

Users::whereColumn('username', 'lastname')->get();