简体   繁体   中英

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:

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? 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:

{ "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:

@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:

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

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

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