Laravel DB::table AND 语句?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28480767/
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
Laravel DB::table AND statement?
提问by EmJeiEn
I'm very new to Laravel and don't quite understand the DB::table
method in conjuction with an AND
clause.
我对 Laravel 很陌生,不太了解DB::table
与AND
子句结合使用的方法。
So I have this query at the moment:
所以我现在有这个查询:
$query = DB::select( DB::raw("SELECT * FROM tablethis WHERE id = '$result' AND type = 'like' ORDER BY 'created_at' ASC"));
It is working, but I'd like to use Laravel's Query Builder to produce something like:
它正在工作,但我想使用 Laravel 的查询生成器来生成类似的内容:
$query = DB::table('tablethis')->where('id', '=', $result)->where('type', '=', 'like')->orderBy('created_at', 'desc')
But this seems to ignore the second where()
completely. So, basically how do I make this work?
但这似乎where()
完全忽略了第二个。那么,基本上我该如何进行这项工作?
回答by Loko
Just adding another ->where
behind another ->where
is the way to get another where
statement
只是在另一个->where
后面添加另一个->where
是获得另一个where
声明的方法
So your code should be fine.
所以你的代码应该没问题。
$query = DB::table('tablethis')->where('id', '=', $result)->where('type', '=', 'like')->orderBy('created_at', 'desc')
There must be something wrong with a different part. I do hope this isn't your full query.
不同的部分一定有问题。我希望这不是您的完整查询。
If it is, you need a ->get()
at the end.
如果是,->get()
则最后需要一个。
回答by Marcin Nabia?ek
For sure this code should work as expected.
可以肯定,此代码应该按预期工作。
I don't know how you check the query executed, but you can go to app/providers/EventServiceProvider.php
(I assume you have L5) and in boot
method add:
我不知道你如何检查执行的查询,但你可以去app/providers/EventServiceProvider.php
(我假设你有 L5)并在boot
方法中添加:
Event::listen(
'illuminate.query',
function ($sql, $bindings, $time) {
$sql = str_replace(array('%', '?'), array('%%', "'%s'"),
$sql);
$full_sql = vsprintf($sql, $bindings);
file_put_contents(storage_path() . DIRECTORY_SEPARATOR .
'logs' . DIRECTORY_SEPARATOR . 'sql_log.sql',
$full_sql . ";\n", FILE_APPEND);
}
);
to see exact SQL that was executed.
查看执行的确切 SQL。
In addition (but it's just improvement) when using =
operator, you can omit it, so you can use here:
另外(但只是改进)在使用=
操作符时,可以省略它,所以你可以在这里使用:
$query = DB::table('tablethis')->where('id', $result)->where('type', 'like')->orderBy('created_at', 'desc');