我如何在 Laravel 4 中将对象转换为字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20976666/
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 I can convert Object to String in laravel 4
提问by Antonio Carlos Ribeiro
I have a function in the model and I return it to a variable like the following
我在模型中有一个函数,我将它返回到一个变量,如下所示
$books = DB::select('select * from books where category_id = 2');
return $books;
And Laravel Query Builder return an object.How I can convert it to the string from the controller? Have a function for that? Please let's me know.
Laravel Query Builder 返回一个对象。如何将其从控制器转换为字符串?有一个功能吗?请让我知道。
回答by Antonio Carlos Ribeiro
What you get from this query
你从这个查询中得到什么
$books = DB::select('select * from books where category_id = 2');
If you do
如果你这样做
var_dump($books);
You'll see that it's an array, not an object.
你会看到它是一个数组,而不是一个对象。
You need a big string with all your records? You can serialize it:
您需要一个包含所有记录的大字符串吗?你可以序列化它:
return serialize($books);
But you'll have to
但你必须
unserialize($value);
to use it.
使用它。
You need to use the values you get from that select? You can use foreach()
on that array:
您需要使用从该选择中获得的值吗?您可以foreach()
在该数组上使用:
foreach($books as $book)
{
echo $book['name'];
}
Or you can do your select differently:
或者您可以以不同的方式进行选择:
$books = Book::where('category_id',2)->get();
And do your foreach using the object notation:
并使用对象表示法进行 foreach:
foreach($books as $book)
{
echo $book->name;
}