【问题标题】:How to make array taking data from database in laravel如何使数组从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;

【问题讨论】:

    标签: sql arrays laravel model-view-controller model


    【解决方案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 已更新答案以显示如何使用已定义的关系。为了后续访问者的利益,您可以将答案标记为已接受
    • 非常感谢.....更新后的答案更好
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-24
    • 2019-03-04
    • 2014-06-05
    • 2021-11-07
    • 1970-01-01
    • 2019-12-15
    • 2018-11-10
    相关资源
    最近更新 更多