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

时间:2018-03-06 21:53:59

标签: php arrays laravel

我正在返回项目团队成员的详细信息。

所涉及的表格是:

 users
 projects 
 members

(为简洁起见,他们看起来像这样)

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

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

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

项目可以有多个成员,成员表实际上是用户的数据透视表。

目前使用此:

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

我想在上面的循环中做的是评估用户记录,然后如果填充了头像字段并且头像类型是特定值,则创建/推送/将另一个字段添加到结果中以便我可以添加在额外的信息。

这样的事情:

$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'")
                }
            }
    });

因此,当我在前端调用这些图像记录时,我可以使用该新字段填充html类。

这样的事情:

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

希望这是有道理的!

如何添加额外的字段?

2 个答案:

答案 0 :(得分:2)

怎么样:

Guess: 10^2
Highest base: 10

Then at minimum we have (10 - 1) + (floor(log2 (10^2)) - 1)
= 15 elements. Too many.


Guess: 5^2 
Highest base: 5
Minimum element count: (5 - 1) + (floor(log2 (5^2)) - 1) = 8

Iterate over logs:
  -- Because of the exponential nature of the problem,
  -- if the guess is too large, the bulk of the elements will appear
  -- early in the iteration; and if it's too small, the limit on
  -- exponents will drop early allowing for early exit in either case.

  [floor(logBase x 25) - 1 | x <- [2..4]] = [3,1,1]
  sum ([1] ++ [3,1,1]) = 6. Too few.


Guess: 7^2
Highest base: 7
Minimum element count: (7 - 1) + (floor(log2 (7^2)) - 1) = 10

Iterate over logs:
  [floor(logBase x 49) - 1 | x <- [2..6]] = [4,2,1,1,1]
  sum ([1] ++ [4,2,1,1,1]) = 10

Answer: 7^2

答案 1 :(得分:1)

现在对于真实雄辩的答案......

你想做的是做

class ProjectTeam
{
    protected $appends = ['imageClass'];

    public function getImageClassAttribute()
    {
        return 'whatever';
    }
}

现在,无论何时拨打$projectTeam->imageClass,您都会获得whatever