Laravel join query with conditions

◇◆丶佛笑我妖孽 提交于 2019-11-27 09:54:24

I'm still not completely sure about your table relationships but from my guess, I came up with the following solution, first create the relationships using Eloquent models:

User Model (for usres table):

namespace App;

use App\Course;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    public function courses()
    {
        return $this->hasMany(Course::class);
    }
}

Course Model (for CoursesAssigned table):

namespace App;

use App\CourseInfo;
use Illuminate\Database\Eloquent\Model;

class Course extends Model
{
    protected $table = 'CoursesAssigned';

    public function courseInfo()
    {
        return $this->belongsTo(CourseInfo::class);
    }
}

CourseInfo Model (for CourseInfo table):

namespace App;

use App\CourseParent;
use Illuminate\Database\Eloquent\Model;

class CourseInfo extends Model
{
    protected $table = 'CourseInfo';

    public function courseParent()
    {
        return $this->belongsTo(CourseParent::class, 'parent_id');
    }
}

CourseParent Model (for CourseParents table):

namespace App;


use Illuminate\Database\Eloquent\Model;

class CourseParent extends Model
{
    protected $table = 'CourseParents';

}

Get the assigned users:

$assignedUsers = User::whereHas('courses', function($query) {
    $query->where('approved', 1)
          ->with(['courses.courseInfo.courseParent' => function($query) {
              $query->where('end_date', >= \Carbon\Carbon::now());
          }]);
})->get(); // paginate(...) for paginated result.

This should work if my assumption is correct. Try this for assignedUsers first then let me know and then I'll look into it for the other requirements. Also make sure that you do understand about Eloquent relationships between models and implement everything correctly (with correct namespace).


Note: This answer is incomplete and need further info because the answer is a result of direct conversation with OP over phone (OP called me because I was reachable) so some changes will be made overtime if needed and will be continued step by step until I can come up with a solution or leave it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!