php Laravel first() vs take(1)->get()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40958306/
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 first() vs take(1)->get()
提问by bawsi
I'm learning laravel, and am kind of following a youtube tutorial where were building a blog. Anyway, I am trying to make a page which shows single blog post, and uses slug instead of id to show it. Anyway, this is my blog controller:
我正在学习 Laravel,并且正在关注正在构建博客的 youtube 教程。无论如何,我正在尝试制作一个显示单个博客文章的页面,并使用 slug 而不是 id 来显示它。无论如何,这是我的博客控制器:
class BlogController extends Controller {
public function getSingle($slug) {
$post = Post::where('slug', $slug)->take(1)->get();
return view('blog/single')->with('post', $post);
}
}
But this way, It wont work.. On my blog/single view, i cant access $post->title for example. But, when I do it like this:
但是这样,它就行不通了。例如,在我的博客/单一视图中,我无法访问 $post->title。但是,当我这样做时:
class BlogController extends Controller {
public function getSingle($slug) {
$post = Post::where('slug', $slug)->first();
return view('blog/single')->with('post', $post);
}
}
.. it works fine. I have access to title, body and created/updated at times.
..它工作正常。我有时可以访问标题、正文和创建/更新。
What is the reason first method wont work?
第一种方法不起作用的原因是什么?
Thank you in advance. :)
先感谢您。:)
回答by Alexey Mezenin
It's because take(1)->get()
will return a collectionwith one element.
这是因为take(1)->get()
将返回一个包含一个元素的集合。
first()
will return element itself.
first()
将返回元素本身。