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

Saturday, February 12, 2022

[FIXED] Laravel Eloquent Subquery with condition

 February 12, 2022     laravel, laravel-8     No comments   

Issue

How to add a subquery to the main query with a condition? The result of the request should be similar to this:

select 
    `tasks`.*, 
    `users`.`name` as `user_name`, 
    (select count(*) from tasks_favorites on tasks_favorites.task_id = tasks.id and tasks_favorites.user_id = 38) as `is_favorite` 
from `tasks` 
left join `users` on `users`.`id` = `tasks`.`user_id` 
where 
    `tasks`.`id` = 149

I try this query but I get an error:

$task = DB::table('tasks')
        ->select(
            'tasks.*', 
            'users.name as user_name',
        )
        ->when(Auth::check(), function($query) {
            return $query->addSelect(
                DB::table('tasks_favorites')->where('tasks_favorites.task_id', 'tasks.id')->where('tasks_favorites.user_id', auth()->user()->id)->count()
            ) ;
        })
        ->leftJoin('users', 'users.id', 'tasks.user_id')
        ->where('tasks.id', $task_id)
        ->get()
        ->first() ;

Solution

did you try the selectRaw or raw method?

something like this

    $task = DB::table('tasks')
        ->select(
            'tasks.*',
            'users.name as user_name',
        )
        ->when(Auth::check(), function($query) {
            return $query->addSelect(
                DB::raw('select count(id) from tasks_favorites where tasks_favorites.task_id=tasks.id AND tasks_favorites.user_id='.auth()->user()->id.' as mycount')
            );
        })
        ->leftJoin('users', 'users.id', 'tasks.user_id')
        ->where('tasks.id', $task_id)
        ->get()
        ->first() ;


Answered By - Aria Shahdadi
  • 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