Laravel 模型属性高级用法定义模型关系

文件位置:

D:\phpStudy\WWW\xxx\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Concerns\HasAttributes.php

隐藏属性:

protected $hidden = ['password'];

显示属性:

protected $visible = ['first_name', 'last_name'];

临时暴露隐藏属性:

return $user->makeVisible('attribute')->toArray();

类似的,如果你想要隐藏给定模型实例上某些显示的属性,可以使用 makeHidden 方法:

return $user->makeHidden('attribute')->toArray();

注意一定要先定义像追加的字段名,这相当于临时给model加字段,所以后面就可以像操作正常字段那样操作。

protected $appends = ['is_admin'];
public function getIsAdminAttribute()
{
    return $this->attributes['admin'] == 'yes';
}

运行时追加:

你可以在单个模型上使用 append 方法来追加属性,或者,你可以使用 setAppends 方法为给定模型覆盖整个追加属性数组:

return $user->append('is_admin')->toArray();
return $user->setAppends(['is_admin'])->toArray();
    protected $appends = ['telephone', 'email'];
    public function getTelephoneAttribute()
    {
        return $this->attributes['telephone'] = $this->customers->telephone;
    }

    public function getEmailAttribute()
    {
        return $this->attributes['email'] = $this->customers->email;
    }
    public function getNotTrailCustomer(Request $request)
    {
        $data = DB::select('SELECT customer.id as customer_id,student_info.id,lesson_appointment.id as lesson_appointment_id FROM (student_info Left JOIN customer ON student_info.customer_id = customer.id ) left JOIN lesson_appointment ON student_info.id = lesson_appointment.student_info_id;');
        $ids = collect($data)->where('lesson_appointment_id', null)
            ->pluck('customer_id')
            ->filter()
            ->toArray();
        $customers = Customer::whereIn('id', $ids)
            ->get(['id', 'chinese_name', 'english_name', 'area_phone_number', 'telephone', 'timezone', 'email', 'wechat', 'country_id'])
            ->makeVisible('country_name')
            ->makeHidden('country_id');

        $title = ['用户编号', '中文名', '英文名', '区号', '手机号', '时区', '邮箱', '微信', '国家'];
        $customers->prepend($title);
        $this->downloadDataList($customers, '还未预约试听课用户', '未预约');
    }

把数组或者集合变成可下载excel文件

    public function downloadDataList($data, $file_name = '访问统计信息表', $sheet_name = '统计信息')
    {
        Excel::create($file_name, function ($excel) use ($data, $sheet_name) {
            $excel->sheet($sheet_name, function ($sheet) use ($data) {
                $sheet->fromModel($data, null, 'A1', false, false)
                    ->freezeFirstRowAndColumn(); #冻结第一行
            });
        })
            ->export('xlsx'); #导出格式为xlsx
    }

相关,定义模型关系:
https://www.jianshu.com/p/d7e5ee17e5ed

你可能感兴趣的:(php,laravel,框架)