简体   繁体   English

如何更改Laravel 5 Collection中的值

[英]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 '. 在集合内部,我有一列称为“ type ”,数据看起来像'A1,A2,A3,''A1,A3,'我想将这些代码从另一个表“ vender_type ”传输为实名。

code name
 A1    XX
 A2    OO
 A3    ZZ

then add a new column into the original collection $VenderData. 然后在原始集合$ 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 : 您必须拆分type属性(使用array explode(string $delimiter , string $string) ),并从vender_type表中获取每个名称,请尝试以下操作:

$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. vender_type可能是数据库中的某些外键,因此您可以在查询生成器中获取该值。 To find out about foreign keys and joins in laravel eloquent check this . 要了解有关外键和laravel雄辩的加入,请检查

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. 只需将table1table2替换为数据库中表名的值即可。

Hope it helps 希望能帮助到你

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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