在LARAVEL中使用eloquent检索单行

时间:2017-02-14 08:04:54

标签: php laravel-5.1

我正在使用laravel 5.1,想要检索数据库中的单行,然后再操作它。

我目前的代码是

$profiles = Profile::where('user_id', $this->user->user_id)
->where('profile_code', $this->user->profile_code)
->get();

foreach($profiles as $profile ){
$data['address'] = $profile->address;
}

为什么我不能这样做?

$profiles = Profile::where('user_id', $this->user->user_id)
->where('profile_code', $this->user->profile_code)
->get();

$data['address'] = $profiles->address;
我正在使用错误的功能吗? 提前谢谢。

2 个答案:

答案 0 :(得分:1)

试试这个:

$data['address'] = $profiles[0]->address;

当您使用get()时,它会返回一个Std类对象数组。

除了检索给定表的所有记录外,您还可以使用first检索单个记录。这些方法不返回模型集合,而是返回单个模型实例:

// Retrieve the first model matching the query constraints...
$flight = App\Flight::where('active', 1)->first();

答案 1 :(得分:0)

laravel 5.8

从配置文件中检索单行/列

如果只需要从数据库表中检索一行,则可以使用first()方法。此方法将返回单个stdClass对象:

$Profile = DB::table('Profiles')->where('user_id', $this->user->user_id)
->where('profile_code', $this->user->profile_code)->first();

如果您甚至不需要一整行,则可以使用value()方法从记录中提取单个值。此方法将直接返回列的值:

$address = DB::table('Profiles')->where('user_id', $this->user->user_id)
->where('profile_code', $this->user->profile_code)->value('address');