Laravel Eloquent Model,根据另一列的值返回列的空白数据

问题描述 投票:0回答:3

我有以下用户模型

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'first_name', 'last_name', 'company', 'mobile', 'mobile_share', 'dob', 'email', 'password', 'active'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function teams()
    {
        return $this->belongsToMany('App\Team', 'team_user', 'team_id', 'user_id');
    }
}

当使用雄辩的查询时,如果mobile等于行中的mobile_share,有没有办法自动返回空的0数据?

laravel laravel-5.5
3个回答
2
投票

是的,accessor完成了这项工作。

public function getMobileAttribute()
{
    if ($this->mobile_share !== 0 && isset($this->attributes['mobile'])) {
        return $this->attributes['mobile'];
    }
}

然后用它轻松调用它。

$user->mobile;

1
投票

好吧,所有答案都应该有效,但你可以内联它! :

public function getMobileAttribute($mobile)
{
    return $this->mobile_share ? $mobile : null;
}

有关更详细的说明:

在getter函数中传递$ mobile允许获取当前的mobile属性,所以基本上,如果$ this-> mobile_share!= 0并且不为null则返回移动设备,如果不是,则返回null


-2
投票

我有一个可以满足您需求的解决方案。 在您的模型中,定义一个getter:

public getMobileAttribute($value)
{
    if (!$this->mobile_share) {
        return null;
    }
    return $value;
}
© www.soinside.com 2019 - 2024. All rights reserved.