Jackson J
Jackson J

Reputation: 1523

Laravel's "with" method returns empty list if I try to select single column

Here is my query:

User::with([
        'roles' => function ($query) {
            $query->select('id AS value', 'display_name AS label');
        }
    ])->with([
        'followers' => function ($query) {
            $query->select('id', 'user_id');
        }
    ])->find($id);

This is what is executed in mysql:

select `id`, `user_id` from `followers` where 
`followers`.`followable_id` in (1) and `followers`.`followable_type` = 'user'

In mysql's console it returs results:

+----+---------+
| id | user_id |
+----+---------+
|  4 |       2 |
|  5 |       3 |
+----+---------+

In json response it is empty:

...
"followers": [],
...

If I omit this line

$query->select('id', 'user_id');

then json response contains

    ...
    "followers" => array:2 [▼
    0 => array:6 [▼
      "id" => 4
      "followable_id" => 1
      "followable_type" => "user"
      "user_id" => 2
    ]
    1 => array:6 [▼
      "id" => 5
      "followable_id" => 1
      "followable_type" => "user"
      "user_id" => 3
    ]
   ]
   ...

What I've tried:

  1. $query->select('id', 'user_id');
  2. $query->select('user_id');
  3. $query->select('id', '*'); // this returns what is shown before

What I need: get list of users ids so that response would contain

...
"followers": [2, 3],
...

I know, i can do foreach after fetching it from database and modify result but why this one does not work?

Upvotes: 0

Views: 447

Answers (2)

sharif854
sharif854

Reputation: 131

In with() function query use addSelect instaead select because when you use select other selection remove

try that hope it's help

Upvotes: 1

everytimeicob
everytimeicob

Reputation: 327

Into your with method from your closures, you should return the Query instance.

Also, if the rendered MySQL query doesn't match what you expect so I think that there is an error with your relationships and/or your MySQL query.

Upvotes: 0

Related Questions