是否可以在不循环所有结果的情况下查询表并显示某些列?
所以,我有这个查询
$shipping = Preferences::where('preferences_id', '=', 1)->get();
现在我试图获取此列
$shipping->option_one
$shipping->option_two
错误显然是
未定义属性:Illuminate \ Database \ Eloquent \ Collection :: $ preferences_option_one
未定义属性: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:参数1传递给Illuminate \ Exception \ WhoopsDisplayer :: display()必须是实例异常,给出TypeError的实例,在第281行的/var/www/html/vendor/laravel/framework/src/Illuminate/Exception/Handler.php中调用,并在/ 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);
}
答案 0 :(得分:0)
$shipping[0]->preferences_option_one
$shipping[0]->preferences_option_two
答案 1 :(得分:0)
您可以使用:
$pluck = $shipping->pluck('column', 'other') $pluck->all()
答案 2 :(得分:0)
问题:
$shipping = Preferences::where('preferences_id', '=', 1)->get();
将返回一个集合,并且您希望拥有一个对象。
所以试试$shipping = Preferences::where('preferences_id', '=', 1)->first();
或其他方法从'preferences_id', '=', 1
答案 3 :(得分:0)
当你从数据库中获取一行时,你不应该在最后使用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 }}
希望它会有所帮助。
答案 4 :(得分:0)
如下所示:
$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