在 Laravel 中无循环地从数据库中获取值

Taking values from database without loop in Laravel

是否可以在不循环所有结果的情况下查询 table 并显示某些列?

所以,我有这个查询

$shipping = Preferences::where('preferences_id', '=', 1)->get();

现在我正在尝试获取这些列

$shipping->option_one
$shipping->option_two

错误很明显

Undefined property: Illuminate\Database\Eloquent\Collection::$preferences_option_one

Undefined property: Illuminate\Database\Eloquent\Collection::$preferences_option_two

我该怎么做?

print_r($shipping)

Array
(
    [0] => stdClass Object
        (
            [preferences_id] => 1
            [preferences_option_one] => Priority Mail
            [preferences_option_two] => Express Mail
        )

)
1

错误:

[2017-05-30 10:06:10] production.ERROR: Symfony\Component\Debug\Exception\FatalErrorException: Uncaught TypeError: Argument 1 passed to Illuminate\Exception\WhoopsDisplayer::display() must be an instance of Exception, instance of TypeError given, called in /var/www/html/vendor/laravel/framework/src/Illuminate/Exception/Handler.php on line 281 and defined in /var/www/html/vendor/laravel/framework/src/Illuminate/Exception/WhoopsDisplayer.php:43

/var/www/html/vendor/laravel/framework/src/Illuminate/Exception/Handler.php 第 281 行

protected function displayException($exception)
{
    $displayer = $this->debug ? $this->debugDisplayer : $this->plainDisplayer;

    return $displayer->display($exception);   <--- line 281
}

/var/www/html/vendor/laravel/framework/src/Illuminate/Exception/WhoopsDisplayer.php:43

public function display(Exception $exception) <-- line 43
{
    $status = $exception instanceof HttpExceptionInterface ? $exception->getStatusCode() : 500;

    $headers = $exception instanceof HttpExceptionInterface ? $exception->getHeaders() : array();

    return new Response($this->whoops->handleException($exception), $status, $headers);
}
$shipping[0]->preferences_option_one
$shipping[0]->preferences_option_two

您可以使用:

$pluck = $shipping->pluck('column', 'other')
$pluck->all()

问题:

$shipping = Preferences::where('preferences_id', '=', 1)->get();

将return一个集合并且你想要一个对象。

所以试试

$shipping = Preferences::where('preferences_id', '=', 1)->first();

或其他方法从 'preferences_id', '=', 1

的结果集合中获取 1 个对象

当你从数据库中获取一行时,你不应该在最后使用 get() 方法。您必须在查询结束时使用 first() 方法。所以只需更改

From 
$shipping = Preferences::where('preferences_id', '=', 1)->get();
To 
$shipping = Preferences::where('preferences_id', '=', 1)->first();
or 
$shipping = Preferences::whereIn('preferences_id', 1)->first();

现在您可以使用

{{ $shipping->option_one }}
{{ $shipping->option_two }} 

希望对您有所帮助。

按如下方式操作:

$shipping = Preferences::where('preferences_id', '=', 1)->get();//it return collection of objects

所以要获得价值,请像这样使用它:

$shipping[0]->option_one

或将方法从 get() 更改为 first()

$shipping = Preferences::where('preferences_id', '=', 1)->first();//it returns single value object 

并获得如下值:

$shipping->option_one