[英]how to select specific columns in laravel
I want to show all values of two specified columns 'first_name' and 'pic' from my 'users' table.我想显示“users”表中两个指定列“first_name”和“pic”的所有值。 I am trying 'pluck' but it showing like json format when echo.
我正在尝试“采摘”,但在回声时它显示为 json 格式。 But I need to show it, something - 'John pic' for all.Please, someone help me.
但我需要展示它,一些东西 - 'John pic' 所有。请有人帮助我。 Here is my sample code in 'index.blade.php' bellow -
这是我在下面的“index.blade.php”中的示例代码 -
<?php
$fName = DB::table('users')->pluck('first_name','pic');
echo $fName;
?>
Use you can simply use select as使用您可以简单地使用 select as
$fName = DB::table('users')->select('first_name','pic')->get();
Since, direct access to database from view is not preferred, you can write this query in controller function,由于从视图直接访问数据库不是首选,您可以在控制器函数中编写此查询,
public function getData(){
$fName = DB::table('users')->select('first_name','pic')->get();
return view('index',compact('fName'));
}
Now, iterate over loop in view file,现在,在视图文件中迭代循环,
@foreach($fName as $name)
// access data like {{$name->first_name}} and {{$name->pic}}
@endforeach
Hope you understand.希望你明白。
You can use this code for retrieving specific column value:您可以使用此代码来检索特定的列值:
//Eloquent: Get specific columns (not all the row). Pluck returns an array.
\App\Model::where('id', 1)->pluck('first_name','pic');
// If you only want to get the result value:
\App\Model::where('id', 1)->value('first_name');
You can get specific columns from a model using get()
method, like您可以使用
get()
方法从模型中获取特定列,例如
PostModel::where('post_status', 'publish')->get(['title', 'content', 'slug', 'image_url'])
pass the list of columns to get([...])
it will retrieve the modal data with specified columns.将列列表传递给
get([...])
它将检索具有指定列的模态数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.