PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, February 12, 2022

[FIXED] Laravel: Merge two query builders

 February 12, 2022     laravel, laravel-query-builder     No comments   

Issue

I have a table of courses which will be free to access or an admin will need to click something to let users see the course.

The course table looks like this:

| id | title          | invite_only | 
|----|----------------|-------------|
| 1  | free course    | 0           |
| 2  | private course | 1           |

Separate from this I have a course_user table, where initially users request access, then admins can approve or deny access:

| id | user_id | course_id | approved | declined |
|----|---------|-----------|----------|----------|
| 1  | 3       | 2         | 1        | 0        |
| 2  | 4       | 1         | 0        | 1        |
| 3  | 4       | 2         | 0        | 0        |

I'd like to index all the courses a user has access to:

class User extends model{
  public function myCourses(){
    $public = $this->publicCourses;
    $invited = $this->invitedCourses;
    return $public->merge($invited);
  }
  public function publicCourses(){
    return $this
      ->hasMany('App\Course')
      ->where('invite_only', false);
  }
  public function invitedCourses(){
    return $this
      ->belongsToMany("\App\Course")
      ->using('App\CourseUser')
      ->wherePivot('approved', 1);
  }
}

How can I make the myCourses function return the results of both publicCourses and invitedCourses by doing only one database query? I'd like to merge the two query builder instances.


Solution

I was able to make a much simpler query, and use Laravel's orWherePivot to extract the correct courses:

public function enrolledCourses()
{
    return $this
      ->courses()
      ->where('invitation_only', false)
      ->orWherePivot('approved', true);
}


Answered By - Djave
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing