如何在Laravel代码中使查找方法起作用?

时间:2019-08-19 08:13:49

标签: laravel eloquent

我是菜鸟,但是我从下面的类似代码中得到了不同的结果

在这种情况下,$ id = 12

public function edit($id)
{
    $post = Post::find($id)->with(['comments'])->first();
    return $post;
}

这将返回ID = 1的帖子

public function edit($id)
{
    $post = Post::where('id', $id)->with(['autor'])->first();
    return $post;
}

这将返回id = 12的帖子

如何使查找方法起作用?

1 个答案:

答案 0 :(得分:0)

您需要知道find($id)等同于where('id', $id)->first()。两者都触发请求调用,例如方法get()count(),...

因此,一旦调用其中之一,就会得到结果。

在您的情况下,在模型实例上(find返回了模型实例),您调用了->with(['comments']),其作用与Post::query()->with(['comments'])相同。

使用新的查询,first()确实完成了应做的工作,获得了第一个条目ID = 1

基本上,您确实运行了2个查询,并获得了第二个查询结果。

对于第一个示例,要使其生效,请在find()之后调用->with(['comments']),而不要先输入。

public function edit($id)
{
    $post = Post::with(['comments'])->find($id);
    return $post;
}

这将是Postnull的实例