【问题标题】:Why get() method on laravel returns multiple when I use find()当我使用 find() 时,为什么 laravel 上的 get() 方法返回多个
【发布时间】:2017-10-04 12:39:41
【问题描述】:

嗨,我写这行是为了获得一个特定的帖子,但是当我在 find() 之后使用 get() 时,虽然我使用了 find() 方法,但它返回了大约 30 个帖子。 $post = Post::find(5) ---- 效果很好 $post = Post::find(5)->get() --- !!! 30 个帖子 我知道 get() 返回多条记录,但我希望当我使用 find() 时,它只给我一个帖子。有人能解释一下它是如何工作的吗?

【问题讨论】:

  • 如果你只想要一条记录,你可以尝试 first() 而不是 get()

标签: laravel orm eloquent


【解决方案1】:

get 方法返回相关模型的集合。

如果你这样做:

Post::find(1)->get();

您将获得与 id 1 的帖子相关的帖子集合。

如果你这样做:

Post::find(30)->get()->find(1);

您将获得该集合的第一个帖子,因为 get 方法正在返回 id 为 30 的帖子所属的帖子集合。

【讨论】:

  • 非常感谢
【解决方案2】:

您不需要将get()find() 一起使用

Post::find(5) \\ return one post of Id: 5

Post::find(5)->get();

将与

一样工作
Post::all()

【讨论】:

  • 第二个和第三个不会返回相同的值。 all() 返回表中的每条记录。
【解决方案3】:
If you use Post::find(1)
it find record that have id 1 and return only that object not collection

but if you use get() then it return collection

in this case

Post::find(1)->get();
it is getting single data with find(1) but after that it run get() so it get all collection of database.
if you want to know how you can simply try by using get() without using find
Post::get(); is equivalent to Post::find(1)->get() or any number

Post::find(1)->get() find(1) is useless here

【讨论】:

    猜你喜欢
    • 2012-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-27
    • 2020-08-26
    • 1970-01-01
    • 2021-04-19
    • 1970-01-01
    相关资源
    最近更新 更多