Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Laravel 4 Eloquent Query Builder - Complicated joins with variable

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 444
    Comment on it

    As we all know joins play an important role in any project . So Laravel 4.x also provide Eloquent Query Builder in which we are able to use Complicated joins with variable.This can be easily explain by using example

    Example:

    I managed to fix this myself, there's a note at the bottom of why it's not completely optimal but here's how to do it anyway:

    public function scopeJoinUserData($query, $user_id)
    {
        return $query->leftJoin('content_userdata', function($join) use ($user_id)
        {
            $join->on('content_userdata_content_id', '=', 'content.content_id')->on('content_userdata_user_id', '=', DB::raw('"'.$user_id.'"'));
        });
    }
    

    Performance: One thing to note is that MySQL queries can be considerably faster when using an integer rather than a string and will interpret it as a string if it's wrapped in quotes. I'm not worrying about that for now, but I figured I should mention it if others are using this as a solution.

    For join we will also use DB::raw() by this we can also perform join by writing direct mysql query.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: