在laravel雄辩的采摘与原始concat奇怪的行为

I had the following ORM which was working

$timezones = DB::table('timezones')->pluck(DB::Raw('concat_ws(" ",label,name) as name'), 'id');

I converted it to

$timezones = Timezone::pluck(DB::Raw('concat_ws(" ",label,name) as name'), 'id');

and got the error like below

ErrorException in Str.php line 432:
Illegal offset type in isset or empty

Model is pretty simple like below

class Timezone extends Model
{

     protected $table = 'timezones';
     protected $connection = 'mysql';

}

I think, Your raw query inside pluck refers to an object. So, when to try to get an element with index as object error has been displayed.

You should change your query to something like this:

$timezones = Timezone::select(DB::Raw('concat_ws(" ",label,name) as name'), 'id')->pluck('name','id');

This will work. Hope it will help

One other way to achieve the same results without having to use DB::raw and MySQL's concat_ws is to use Laravel's Accessors. So for example:

On your Timezone model, create an accessor method like this:

public function getLabelAttribute($value)
{
    return $value . ' ' . $this->name;
}

Then you can retrieve that by doing this:

$timezone = Timezone::first();
$timezone->label;