Laravel Eloquent 模型,return 列的空白数据基于另一列的值

Laravel Eloquent Model, return blank data for column based on value of another column

我有以下用户模型

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

当使用 eloquent 查询时,如果行中的 mobile_share 等于 0,是否有办法自动 return 清空 mobile 数据?

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

public getMobileAttribute($value)
{
    if (!$this->mobile_share) {
        return null;
    }
    return $value;
}

是的,accessor 可以。

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

然后用.

轻松调用它
$user->mobile;

好吧,所有答案都应该有效,但您可以将其内联! :

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

更详细的解释:

在您的 getter 函数中传递 $mobile 允许获取当前的 mobile 属性,所以基本上,如果 $this->mobile_share != 0 并且不为空,则 return 手机,如果不是,return null