【问题标题】:Queries in Laravel - Equivalent to left joinLaravel 中的查询 - 相当于左连接
【发布时间】:2020-06-09 05:09:58
【问题描述】:

目前这是我的 laravel 查询

    $response['appointMent'] = $this->appointment->where('user_id', Auth::guard('user')->user()->id)
    ->whereIn('status', array('Sched', 'Going', 'Request Appointment'))
    ->whereDate('set_date', '>', Carbon::now()->subDays(1))
    ->with(['company'])
    ->with(['applicant'])
    ->with(['job'])
    ->with(['user'])->get();

但是很遗憾,我还想获取公司和用户表之间的连接数据,公司的user_id和用户的id

这是表公司表:

和用户表

如何连接公司数组下的用户?

【问题讨论】:

    标签: php sql laravel eloquent


    【解决方案1】:

    您需要像这样为公司与用户建立关系

    公司模式

    public function user()
    {
       return $this->belongsTo(Company::class,'user_id');
    }
    

    你的查询将变成

    response['appointMent'] = $this->appointment->where('user_id', Auth::guard('user')->user()->id)
                    ->whereIn('status', array('Sched', 'Going', 'Request Appointment'))
                    ->whereDate('set_date', '>', Carbon::now()->subDays(1))
                    ->with(['company.user','applicant','job'])->get();
    

    现在用户关系将在公司内部

    或者反过来 用户模型

    public function company()
    {
       return $this->hasOne(User::class); //Or hasMany depends on your needs
    }
    

    那么下面的查询就会变成

    response['appointMent'] = $this->appointment->where('user_id', Auth::guard('user')->user()->id)
                    ->whereIn('status', array('Sched', 'Going', 'Request Appointment'))
                    ->whereDate('set_date', '>', Carbon::now()->subDays(1))
                    ->with(['user.company','applicant','job'])->get();
    

    【讨论】:

    • 我已经稍微调整了代码,我刚刚破解了它!谢谢!!
    • 享受你的一天:)
    最近更新 更多