如何使数组从 laravel 中的数据库中获取数据

How to make array taking data from database in laravel

为什么我的所有查询都单独工作时这不起作用。

$data = [
    'name' => $user->name,
    'email' => $user->email,
    'phone' => $profile->phone,
    'address' => $profile->address,
    'gender' => $profile->gender,
];

return$数据;

这就像手动工作一样

$data = [
    'name' => 'my_name',
    'email' => 'my_email',
    'phone' => 'my_phone',
    'address' => 'my_address',
    'gender' => 'my_gender',
];

return$数据;

我的全部功能如下:

 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() 时,它 returns 是一个集合而不是单个对象,因此您可以

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;
}