Laravel明确加入一对多

时间:2018-06-04 09:03:47

标签: php mysql laravel eloquent greatest-n-per-group

我在网上发现了几个与我类似的问题,但我似乎无法找到合适的答案。

我有2张桌子

用户

ID | FIRSTNAME  | EMAIL_ADDRESS
1  | Joe Bloggs | Joe@bloggs.com

状态

ID | USER_ID | STATUS | DATE
1  |  1      | 'In'   | 2018-06-04 09:01:00
2  |  1      | 'Out'  | 2018-06-04 09:00:00

我需要能够将2个表连接在一起,但只能按date获取最新的状态列,如下所示

ID | FIRSTNAME  | EMAIL_ADDRESS    | STATUS_ID | STATUS | DATE
1  | Joe Bloggs | Joe@bloggs.com   | 1         | 'In'   | 2018-06-04 09:01:00

我需要能够运行额外的查询构建器参数,例如where,因为用户可以在需要时传入过滤器和搜索参数,以便能够使用我的状态表列查询构建器,我正在进行这样的连接

$users = Users::join('status', 'status.user_id', '=', 'user.id')->distinct('user.id');

然后,如果我需要,我可以传入任何搜索参数

         if(!empty($request->search)){
             $param = $request->search;
             $users = $users->where(function($query) use ($param){
                 $query->where('users.firstname', 'like', '%'.$param.'%')
                       ->orWhere('users.email_address', 'like', '%'.$param.'%');
             });
         }
         if(!empty($request->dateFrom)){
             if(!empty($request->dateTo)){
                 $users = $users->whereRaw('DATE(status.date) BETWEEN ? AND ?', [$request->dateFrom, $request->dateTo]);
             } else {
                 $users = $users->whereRaw('DATE(status.date) BETWEEN ? AND DATE(NOW())', [$request->dateFrom]);
             }
         }

然后在最后运行我的get()

    if($method == 'paginate'){
        $users = $users->paginate(10);
    } else {
        $users = $users->get();
    }

返回以下内容

ID | FIRSTNAME  | EMAIL_ADDRESS    | STATUS_ID | STATUS | DATE
1  | Joe Bloggs | Joe@bloggs.com   | 1         | 'In'   | 2018-06-04 09:01:00
2  | Joe Bloggs | Joe@bloggs.com   | 1         | 'Out'  | 2018-06-04 09:00:00

我需要能够在我的Where函数中使用外部表列作为参数,但我需要每个用户只返回1行。如何运行联接,但每个用户只返回1行?

2 个答案:

答案 0 :(得分:1)

要获取每个用户的最新记录,您可以使用状态表的自联接

select u.*,s.*
from user u
join status s on u.id  = s.user_id
left join status s1 on s.user_id = s1.user_id 
and s.date < s1.date 
where s1.user_id is null

使用查询构建器,您可以将其重写为

DB::table('user as u')
  ->select('u.*', 's.*')
  ->join('status as s', 'u.id ', '=', 's.user_id')
  ->leftJoin('status as s1', function ($join) {
        $join->on('s.user_id', '=', 's1.user_id')
             ->whereRaw(DB::raw('s.date < s1.date'));
   })
  ->whereNull('s1.user_id')
  ->get();

Laravel Eloquent select all rows with max created_at

Laravel - Get the last entry of each UID type

Laravel Eloquent group by most recent record

答案 1 :(得分:0)

由于您使用的是Laravel,因此让解决方案更容易理解和简单: First让我们为每个表创建模型:

class User extends Model
{
    public $timestamps = false;

    protected $fillable = [
       'FIRSTNAME', 
       'EMAIL_ADDRESS'
    ];

    public function status(){
    return $this->hasMany(\App\Status::class);
}
}

现在让我们创建状态模型:

class Status extends Model
{
    public $timestamps = false;

    protected $casts = [
        'USER_ID' => 'int',
    ];

    protected $fillable = [
        'USER_ID',
       'STATUS',
        'DATE'
    ];

    public function user()
    {
        return $this->belongsTo(\App\User::class);
    }
}

现在你可以像这样使用Eloquents:

 $result=User::whereHas('Status', function($q){
    $q->where('date', $current_date);
})->distinct('id')->get();

希望它有帮助!