如何在 Laravel 中编写 MySql 查询

问题描述 投票:0回答:2

如何在 Laravel 中编写下表的查询。 就像在我的应用程序中登录的用户 ID 是 109 所以我需要谁的用户与 BlindDate 和 PaidDate 表中的登录用户匹配到用户 ID。

This is User table

This is BlindDate table

THis is PaidDate table

我想要的预期输出是:

data[
  
  'blind_users':[
     {
        'uuid':'rvfv',
        'user_id':109,
        'touser':[
            {
              'name':'james',
              'email':'[email protected]'
            }  
         ]

     },
     {
        'uuid':'rvfv',
        'user_id':109,
        'touser':[
            {
              'name':'james',
              'email':'[email protected]'
            }  
         ]

     },
  ],

 'paid_date_users':[
   {
        'uuid':'rvfv',
        'user_id':109,
        'touser':[
            {
              'name':'james',
              'email':'[email protected]'
            }  
         ]

     },
  ]

]
mysql laravel eloquent phpmyadmin
2个回答
-1
投票

希望您已经设置了雄辩的模型及其关系,因为您在这个项目中使用了 Laravel!

如果你只有用户 ID,你可以像这样查询用户模型

return User::with('blind_date', 'paid_date')->where('id', $userId)->first();

如果您有经过身份验证的用户,您可以直接返回用户而无需任何急切加载,或者只需在刀片中调用它,如

auth()->user()


-1
投票

Ans: 在用户模型中使用这两个函数。

public function bind_dates(){
  return $this->belongsTo('binddates','user_id');
}
    
public function free_paid_dates(){
  return $this->belongsTo('freepaiddates','user_id');
}

查询:

Users::with('free_paid_dates','bind_dates')->where('id',$user_id)->get();

如果您有多个用户,则用户

hasMany
关系。

请使用此代码,我认为您的代码可以正常工作。

© www.soinside.com 2019 - 2024. All rights reserved.