laravel where子句值和列名

时间:2018-05-09 06:56:50

标签: mysql laravel

我如何在laravel query where子句中执行这些操作?

select * from table_samples where 1 = id 
// basically i can do like where id = 1

select * from table_samples where 1000 > rate
 // basically i can do like where rate < 1000

select * from table_samples where 'bogart' = name
 // basically i can do like where name = "bogart"

我的观点是,如果你交换columnvalue它在mysql上的工作,但是如果我在laravel where子句中这样做它不起作用吗?

这样的东西
TableSample::where('1','id')->first();
TableSample::where('1000','>','rate')->first();
TableSample::where('bogart','name')->first();
// throws an error undefined column name 1, 100, and bogart.

// I know laravel . These are the correct query
TableSample::where('id','1')->first();
TableSample::where('rate','<','1000')->first();
TableSample::where('name','bogart')->first();

laravel中是否有where子句可以接受或确定您是否尝试交换valuecolumn

2 个答案:

答案 0 :(得分:1)

你可以使用DB::raw()

TableSample::whereRaw('? = id', [1])->first();

请确保使用上述参数替换来防止创建SQL注入漏洞。

https://laravel.com/docs/5.6/queries#raw-expressions

答案 1 :(得分:0)

  

whereRaworWhereRaw方法可用于将raw where子句注入查询

TableSample::whereRaw('1 = id')->first();

https://laravel.com/docs/5.6/queries#raw-methods