sql - 如何使数组从laravel中的数据库中获取数据
问题描述
为什么在我所有的查询都单独工作的情况下这不起作用。
$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;
解决方案
使用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;
}
推荐阅读
- sql - Microsoft Access 使用 ROW_NUMBER 的替代方法查询重复日期
- typescript - 如何使用类型脚本在量角器中获取每次点击的状态代码以验证点击后显示的页面不会像 400 代码那样崩溃
- typescript - 如何从装饰器中的装饰属性解析属性值的通用类型
- javascript - Prisma Connection WhereInput 用于枚举值数组?
- google-apps-script - 如果在设定的时间内没有按下键盘,你可以触发一个函数在谷歌应用程序脚本中运行吗?
- visual-studio-code - 多根工作区有没有办法构建所有项目?
- sql - 为什么 STATS_CROSSTAB CHISQ_SIG 在 Oracle SQL 中没有返回正确的 p 值?
- c++ - 当在声明它的父类的实例上调用纯虚函数时会发生什么?
- java - 为什么这个 if 语句不能正确执行?
- apache-spark - SparkSQL 查询执行比我的数据库慢