查询构建器中的Laravel Mutator?

问题描述 投票:2回答:2

我不知道如何在查询构建器中使用mutator将两个字段定义为一个字段,这是我的代码

$model = LoanInformation::select( 
    'basic_information.first_name', 'basic_information.last_name',
    'loan_information.id', 'loan_information.tenor'
)->join(
    'basic_information', 'loan_information.user_id', '=', 'basic_information.user_id'
)->where(
    'loan_information.status', 'funding'
)->paginate(9);

如何将first_name和last_name定义为name并在其上添加返回strtoupper(first_name)strtoupper(last_name)的语句

laravel laravel-5
2个回答
1
投票

对于LoanInformation模型,添加以下方法:

public function getNameAttribute() {
    return strtoupper($this->first_name . ' ' . $this->last_name);
}

这将使您能够编写$model->name,它将返回firstname和lastname,以空格连接,全部为大写。


0
投票

我只是通过向数组添加键和值而不是mutator或accessor来解决这个问题

这是我自己的答案

$model = LoanInformation::select(
       'loan_information.id', 'loan_information.tenor',
       'basic_information.first_name', 'basic_information.last_name'
)->leftjoin(
       'basic_information', 'loan_information.user_id', '=', 
       'basic_information.user_id'
)->where('loan_information.status', 'funding')
->orderBy('loan_information.created_at', 'ASC')
->paginate(9);

foreach($model as $key => $value) {
   $tx_funding = TxFunding::whereLoanId($value->id)->get();
   $name = substr($value->first_name, 0, 1).substr($value->last_name, 0, 2);

   $model[$key]['name'] = strtoupper($name);
   $model[$key]['grade'] = 'A+';
   $model[$key]['fundraiser'] = $tx_funding->count();
   $model[$key]['progress'] = 50;
   $model[$key] = array_except($value, ['first_name', 'last_name']);
}

return response()->json($model);
© www.soinside.com 2019 - 2024. All rights reserved.