简体   繁体   中英

How to change the value in laravel 5 collection

I have some problems here. I get a collection which like:

$VenderData=Vender::where('active', '=', '1')->get();

Inside the collection i have a column called ' type ' and the data looks like 'A1,A2,A3,' or 'A1,A3,' I want to transfer those codes to real names from another table ' vender_type '.

code name
 A1    XX
 A2    OO
 A3    ZZ

then add a new column into the original collection $VenderData.

How can i do this?

You must split the type attribute (using array explode(string $delimiter , string $string) ) , and get the name of each one from vender_type table, try this :

$VenderData = Vender::where('active', '=', '1')->get();
foreach($VenderData as $vend)
{
     $vend->new_type = array();
     $types = explode(",", $vend->type);
     foreach($types as $type)
     { 
         $t = vender_type::where('code', $type)->first();
         if($t)
             $vend->name_type[] = $t->name;
             // or for example : $vend->name_type[$type] = $t->name;
     }
}

I hope that will help you.

I think that you need better query than modifying each value after. This vender_type is probably some foreign key in you database so you can get that value in query builder. To find out about foreign keys and joins in laravel eloquent check this .

Basically you need something like this

$users = DB::table('table1')
        ->join('table2', 'table1.vender_type', '=', 'table2.vender_type')
        ->select('table1.code', 'table1.name', 'table2.vender_type')
        ->where('table1.active', '=', '1')
        ->get();

Just replace table1 and table2 with values of you table names in database and you're done.

Hope it helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM