首页 > 解决方案 > 如何使数组从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;

标签: sqlarrayslaravelmodel-view-controllermodel

解决方案


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

推荐阅读