如何使数组从laravel中的数据库中获取数据
Posted
技术标签:
【中文标题】如何使数组从laravel中的数据库中获取数据【英文标题】:How to make array taking data from database in laravel 【发布时间】:2021-03-24 04:57:24 【问题描述】:为什么在我的所有查询都单独工作的情况下这不起作用。
$data = [
'name' => $user->name,
'email' => $user->email,
'phone' => $profile->phone,
'address' => $profile->address,
'gender' => $profile->gender,
];
返回$数据;
这可以像手动一样工作
$data = [
'name' => 'my_name',
'email' => 'my_email',
'phone' => 'my_phone',
'address' => 'my_address',
'gender' => 'my_gender',
];
返回$数据;
我的整个功能如下:
public function read($id)
$user=DB::table('users AS t1')
->select('t1.name','t1.email')
->where('t1.id',$id)->get();
$profile=DB::table('profiles AS t1')
->select('t1.phone','t1.gender','t1.occupation','t1.address')
->where('t1.user_id',$id)->get();
$data = [
'name' => $user->name,
'email' => $user->email,
'phone' => $profile->phone,
'address' => $profile->address,
'gender' => $profile->gender,
];
return $data;
【问题讨论】:
【参考方案1】:当使用get()
时,它返回一个集合而不是单个对象,所以你可以这样做
public function read($id)
$user=DB::table('users AS t1')
->select('t1.name','t1.email')
->where('t1.id',$id)->first();
$profile=DB::table('profiles AS t1')
->select('t1.phone','t1.gender','t1.occupation','t1.address')
->where('t1.user_id',$id)->first();
$data = [
'name' => $user->name,
'email' => $user->email,
'phone' => $profile->phone,
'address' => $profile->address,
'gender' => $profile->gender,
];
return $data;
或者,如果您在模型上定义了关系,则可以使用该关系
class User extends Model
public function profile()
return $this->hasOne(Profile::class);
class Profile extends Model
public function user()
return $this->belongsTo(User::class);
public function read($id)
$user = User::with('profile')->findOrFail($id);
$data = [
'name' => $user->name,
'email' => $user->email,
'phone' => $user->profile->phone,
'address' => $user->profile->address,
'gender' => $user->profile->gender
];
return $data;
【讨论】:
@MunnaKhandakar 已更新答案以显示如何使用已定义的关系。为了后续访问者的利益,您可以将答案标记为已接受 非常感谢.....更新后的答案更好以上是关于如何使数组从laravel中的数据库中获取数据的主要内容,如果未能解决你的问题,请参考以下文章