如何在 Laravel 中执行 where 子句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14218988/
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
How to do a where clause in Laravel
提问by sehummel
I'm trying to build a call to my database with a where clause in Laravel 4. Sounds simple enough, but I'm getting an error that makes no sense. This call works:
我正在尝试使用 Laravel 4 中的 where 子句构建对我的数据库的调用。听起来很简单,但我收到了一个毫无意义的错误。此调用有效:
return MainContact::all();
When I view that page, I get a JSON representation of my data, with all of my data, like you'd expect. It includes this:
当我查看该页面时,我会得到我的数据的 JSON 表示,以及我的所有数据,就像您期望的那样。它包括:
... "flag":1 ...
So when I try to do this, as explained in the Laravel documentation:
因此,当我尝试这样做时,如 Laravel 文档中所述:
return MainContact::where('flag', '=', '1');
you would think it would work, but it doesn't. I've tried the number as both a string and integer, and neither works. I get this error:
你会认为它会起作用,但它不会。我已经尝试将数字作为字符串和整数,但都不起作用。我收到此错误:
ErrorException: Catchable Fatal Error: Object of class
Illuminate\Database\Eloquent\Builder could not be converted to string in
/Users/universal/Sites/universalLaser/leads/vendor/symfony/http-foundation/Symfony/
Component/HttpFoundation/Response.php line 351
Has something changed with where clauses in Laravel 4? Or am I not understanding how to do them?
Laravel 4 中的 where 子句有什么改变吗?还是我不明白该怎么做?
回答by aowie1
have you tried:
你有没有尝试过:
return MainContact::where('flag', '=', '1')->get();
or more simply:
或更简单地说:
return MainContact::where_flag(1)->get();
回答by Cody Covey
You need to call get()
method on the end there.
你需要get()
在那里调用方法。
return MainContact::where('flag', '=', '1')->get();
回答by minhquy
Thank you for guide!
谢谢指导!
I use the categories table:
我使用类别表:
- id
- name
- parent_id
- ID
- 姓名
- parent_id
And route via:
并通过以下路线:
<?php
Route::get('/', function()
{
return Categories::where('parent_id', '>', 0);
});
A return error is Object of class Illuminate\Database\Eloquent\Builder could not be converted to string
返回错误是 Object of class Illuminate\Database\Eloquent\Builder 无法转换为字符串
So I try ->get() in end code it is working.
所以我尝试 ->get() 在它正在工作的最终代码中。