doujingqu3030 2018-03-06 21:53
浏览 37
已采纳

在Laravel / PHP中将一个额外的字段推入一个数组中

I am returning project team member details.

The tables involved are:

 users
 projects 
 members

(edited for brevity they look like this)

'users'
    ('id',
    'name',
    'email',
    'avatar',
    'avatar_type',
    'status')

'projects'
    ('id',
    'name',
    'description')

'members'
    ('id',
    'user_id',
    'position',
    'capacity')

Projects can have multiple members and the members table is effectively a pivot table for the users.

Currently using this:

$projectTeam = [];
$project[0]->members()
    ->with('users')
    ->where('user_id','!=',0)
    ->where('status','=',"Active")
    ->get()
    ->each(function ($member) use(&$projectTeam)
    {
        $projectTeam[$member->id] = $member->users;
    });

What I would like to do in the loop above is to evaluate the user record and then if the avatar field is populated and the avatar type is a certain value create/push/append another field into the results so that I can add in extra information.

Something like this:

$projectTeam = [];
$project[0]->members()
    ->with('users')
    ->where('status','=',"Active")
    ->get()
    ->each(function ($member) use(&$projectTeam)
    {
        $projectTeam[$member->id] = $member->users;

            if($member->users->avatar<>"")
            {
                if($member->users->avatar-type=="1")
                {
                    array_push($projectTeam[$member->id], "imgClass='alpha'")
                }
                if($member->users->avatar-type=="2")
                {
                    array_push($projectTeam[$member->id], "imgClass='beta'")
                }
            }
    });

So that when I call those image records on the front end I can just populate the html class with that new field.

Something like this:

<img src="{{$teammember->avatar}}" class="{{$teammember->imgClass" /> 

Hope this makes sense!

How do I go about adding in that extra field?

  • 写回答

2条回答 默认 最新

  • dongtuhe0506 2018-03-06 22:31
    关注

    How about:

    $projectTeam[$member->id]->imgClass = 'alpha'
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 类图中关联与聚合的区别
  • ¥15 ENVI高分五号去除云层的方法
  • ¥15 16进制数据如何得到奇偶校验位
  • ¥15 求合并两个字节流VB6代码
  • ¥15 Pyqt 如何正确的关掉Qthread,并且释放其中的锁?
  • ¥30 网站服务器通过node.js部署了一个项目!前端访问失败
  • ¥15 WPS访问权限不足怎么解决
  • ¥15 java幂等控制问题
  • ¥15 海湾GST-DJ-N500
  • ¥15 氧化掩蔽层与注入条件关系