简体   繁体   English

Laravel如何在雄辩模型中通过id正确处理值

[英]Laravel How to properly handle values by id in an Eloquent Model

I have a Contact model like this 我有这样的联系人模型

class Contact extends Eloquent
   {
   protected $table = "contacts";

   protected $position = array("frontend developer",
                               "light switch manager",
                               "product designer",
                               "head of tea kitchen");
   }

In my contacts table I want to store the contact's position using the $position array index as position-id, eg: 在我的联系人表中,我想使用$ position数组索引作为position-id来存储联系人的位置,例如:

id     name               pos_id   email
--------------------------------------------------
1      George Teapotter   3        gtpot@maile.com

Now how would I effectively resolve the corresponding array string for the pos_id when querying the Contact model? 现在,在查询联系人模型时,如何有效地解析pos_id的对应数组字符串? I would need something like this in my query: 我在查询中需要这样的内容:

Contact::Select(name, **position(pos_id)**, email)->get();

to get as result for returning as json: 获得作为返回为json的结果:

{ "George Teapotter", "head of tea kitchen", "gtpot@maile.com" }

Thanks for any hints. 感谢您的任何提示。

you can do this easily with PHP, you don't need to do with mysql, your returned result is $rows so you can do this when you loop your result like this: 您可以使用PHP轻松地做到这一点,不需要使用mysql,返回的结果是$ rows,因此当您像这样循环结果时可以这样做:

@foreach($rows as $row) 
<tr>
<td>{{$row->name}}</td>
<td>{{$position[$row->pos_id]}}</td>
<td>{{$row->email}}</td>
</tr>
@endforeach

if you want json encoded you can loop your result to do: 如果您想对json进行编码,则可以循环执行结果:

<?php 
foreach($rows as $row) {
    $row->pos_id = $position[$row->pos_id];
}
?>

最好的方法是在数据库中为您的位置创建另一个表,因为这意味着您也可以利用Eloquent关系...如果您渴望加载关系,几乎不会有任何性能开销。

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

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