0

I have the following in Laravel 4.x using eloquent:

Book table has a dozen fields.

$single_data = Book::
            selectRaw("GROUP_CONCAT(DISTINCT CAST(id as char) SEPARATOR ',') as type_id_list")
            ->first();

Question: the data returned is everything within the table inside Book AND type_id_list as seen from the selectRaw.

I would like to ONLY return what I specified within the selectRaw.

It was suggested that you get add an array of columns within first() or get() in order to retrieve this only - however it is not working with custom selectRaw where you specify an expression or your own wording. It throws an error and when the query is analyzed the array that you put in first/get gets appended as part of the select.

Does anyone have a work around?

9
  • 1
    Does first([]) work? Commented Jun 27, 2014 at 10:58
  • @Andreas ah, it does work too - but I will use pluck instead as it gives back the value itself immediately and not the object too. Commented Jun 27, 2014 at 13:53
  • You should probably report this as a bug. github.com/laravel/framework/issues Commented Jun 27, 2014 at 14:06
  • @Andreas you suggested it first - take the credit. Commented Jun 27, 2014 at 14:08
  • first() and first([]) gives exactly the same result, which is a Book model with single attribute type_id_list (and other properties unrelated to the query like exists etc) because Eloquent provided with selectRaw ignores any previous selects. Given multiple selectRaw methods, it will use only last one. Commented Jun 27, 2014 at 15:05

1 Answer 1

1

first() will return only that particular column but wrapped in a Book object anyway, so use pluck() instead:

$single_data = Book::
        selectRaw("GROUP_CONCAT(DISTINCT CAST(id as char) SEPARATOR ',') as type_id_list")
          ->pluck('type_id_list');
Sign up to request clarification or add additional context in comments.

1 Comment

Note: Andreas' comment first([]) will yield the correct result but I will need to do ->type_id_list to get the info.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.