如何在 Laravel Eloquent 中选择特定字段?


Laravel Eloquent 提供了许多从表中选择所需字段的方法。以下是一些示例,展示了如何实现。

示例 1

以下是一个示例:

<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\User; class UserController extends Controller { public function index() { $users = User::select('name', 'email')->where('id', 1)->get(); foreach ($users as $u) { echo $u->name."=>".$u->email; } } }

输出

以上代码的输出为:

Siya Khan=>[email protected]

以上示例等同于以下 SQL 查询:

SELECT name, email FROM users WHERE id=1;

以上代码的输出为:

+-----------+----------------+
| name      |       email    |
+-----------+----------------+
| Siya Khan | [email protected] |
+-----------+----------------+

示例 2

另一种从表中获取字段的方法如下所示:

<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\User; class UserController extends Controller { public function index() { $users = User::where('id', 1)->get(['name','email']); foreach ($users as $u) { echo $u->name."=>".$u->email; } } }

输出

以上代码的输出为:

Siya Khan=>[email protected]

示例 3

在下面,我们使用了all()方法以及我们需要的表字段。它将获取表中所有数据以及字段值。

它的 SQL 查询为:

SELECT name, email from USERS;
示例如下所示:
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\User; class UserController extends Controller{ public function index() { $users = User::all('name','email'); foreach ($users as $u) { echo $u->name."=>".$u->email." "; } } }

输出

以上代码的输出为:

Siya Khan=>[email protected]
Heena Khan=>[email protected]
Seema=>[email protected]
Neha Singh=>[email protected]
d7jhMWRMQe=>[email protected]
k118AjAswp=>[email protected]
7ZH2Vk0TAp=>[email protected]
w8QSXDIBVU=>[email protected]
feO56tC0sO=>[email protected]
MntJcvWT2L=>[email protected]
RANLQbtj44=>[email protected]
bben5rsdVv=>[email protected]

示例 4

使用pluck()方法获取字段,如下所示:

<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\User; class UserController extends Controller { public function index() { $users = User::where('id', 1)->pluck('name', 'email')->all(); print_r($users); } }

输出

以上代码的输出为:

Array ( [[email protected]] => Siya Khan )

示例 5

使用find()方法获取我们需要的字段。

语法为:

Model::find(valuetobeserarched, ['field1', 'field2']);

示例如下所示:

<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\User; class UserController extends Controller { public function index() { $users = User::find(1, ['name', 'email']); print_r($users); } }

输出

以上代码的输出为

attributes:protected] => Array(
   [name] => Siya Khan
   [email] => [email protected]
)

更新于: 2022年8月30日

8K+ 阅读量

启动你的 职业生涯

通过完成课程获得认证

开始学习
广告