Laravel DB:first()方法带来的响应内容必须是字符串

use*_*988 2 php laravel eloquent

我使用 Laravel Illuminate,当我使用 first() 方法获取单个结果时出现此错误:

The Response content must be a string or object implementing __toString(), "object" given.

return DB::table('todos')->where("title","your List")->first();
Run Code Online (Sandbox Code Playgroud)

如果我使用 get() 方法进行选择,它会起作用:

return DB::table('todos')->where("title","your List")->get();
Run Code Online (Sandbox Code Playgroud)

你知道第一个陈述有什么问题吗?

Joe*_*inz 5

当你这样做时->get(),你会得到一个Illuminate\Support\Collection对象。该对象可以由响应返回,因为它实现了一个__toString()方法:

/**
 * Convert the collection to its string representation.
 *
 * @return string
 */
public function __toString()
{
    return $this->toJson();
}

/**
 * Get the collection of items as JSON.
 *
 * @param  int  $options
 * @return string
 */
public function toJson($options = 0)
{
    return json_encode($this->jsonSerialize(), $options);
}

/**
 * Convert the object into something JSON serializable.
 *
 * @return array
 */
public function jsonSerialize()
{
    return array_map(function ($value) {
        if ($value instanceof JsonSerializable) {
            return $value->jsonSerialize();
        } elseif ($value instanceof Jsonable) {
            return json_decode($value->toJson(), true);
        } elseif ($value instanceof Arrayable) {
            return $value->toArray();
        } else {
            return $value;
        }
    }, $this->items);
}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,它所做的就是将整个集合转换为 json。

但是当你这样做时->first(),幕后发生的事情是 Laravel 所做的->take(1)->get()->first(),这样查询就被限制在一行,然后检索包含该行结果的集合,最后你得到一个对象。

因此,->first()调用是在幕后对集合进行的,这意味着您不会得到另一个集合,而是一个数据库对象 - 可能是这种类型Illuminate\Database\Query\Builder,我不太记得了。

由于该类没有实现__toString()方法,因此响应不知道如何处理它。相反,您会收到错误。

json_encode()您可以通过在对象上运行或返回 json 响应来轻松模拟相同的响应。