'Callback in with() returns null in laravel eloquent query

I'm trying to use laravel eloquent to process a query but it doesn't recognize the relationship

$query = $site
    ->consumers()
    ->with([
        'transactions' => function($_query) use ($thresh) {
            $_query
                ->where('status', 'processed')
                ->where('approved', 1)
                ->selectRaw("SUM({$thresh} - value + bonus_value) AS total_points");
        }
    ])
    ->where('total_points', '<=', 5000);

dd($query->get()->toArray());

I have this code. When I add selectRaw in transactions relationship it returns nothing but when I remove it, it returns all the transactions associated with consumer. Also, total_points in where clause raises issue that total_points not found.

I'm basically trying to get consumers who have total points less than or equals to 5000.



Solution 1:[1]

The reason why this could occur is because you have not set any relation that you are trying to retrieved. For example maybe the foreign keys column names are not correct or values mismatched.

lets say in App/Models/Post.php you have this relationship


public function users(){

return $this->belongTo(User::class, 'user_id', 'user_id');
}

If the column user_id in post table is found but value did not match that off App/Models/User.php the relationship will return a null value when called. So, try checking your relationship foreign and local keys first.

Hope this helps you investigate you bug!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 OBI PASCAL BANJUARE