我有2个两个表:一个是准入表,另一个是类表。我通过json_encode
方法将类ID保存在准入表的准入类字段中。
我的控制器
public function store(Request $request)
{
$inputs = $request->all();
$admission = new Admission;
$admission->school_id = Auth::User()->id;
$admission->admission_classes=json_encode($inputs['admission_classes']);
$admission->save();
}
我的索引功能
public function index(Request $request) {
$school_id= Auth::user()->id;
$admissions= Admission::where('school_id',$school_id)->orderBy('id','desc')->paginate(10);
return view('frontend.index',compact('admissions','active_class'));
}
我的观点
@foreach($admissions as $i => $admission)
{{ $admission->admission_classes }}
@endforeach
我以这种方式获取数据:-
["1","2","4","5","6","7","8","9"]
但是我想使用这种格式:
Nursery,Class 1, Class2, Class3 etc
My class controller
class Classes extends Authenticatable
{
use EntrustUserTrait;
use Billable;
use Messagable;
protected $fillable = [
'name','status'
];
}
答案 0 :(得分:0)
实现此目标的最佳方法是与App\Classes
建立一对多关系。
但是,由于您已经启动并运行了某些程序,因此我可能会这样做。
首先,我将admission_classes
转换为数组。这确保了在每次取入准入类时始终将其强制转换为数组。它使我们更容易使用它。
protected $casts = [
'admission_classes' => 'array'
];
最后,在获取录取记录时,您还需要在其上进行映射并从其ID中填充Classes
。这就是我尝试实现的方式。
$admissions = Admission::where('school_id',$school_id)
->orderBy('id','desc')
->paginate(10)
->map(function($admission) {
return array_map(function($class) {
$class = Classes::find($class);
return isset($class) ? $class->name : '';
}, $admission->admission_classes);
});
您会注意到,我将Classes::find()
方法包装到了optional()
帮助器中。这是因为,如果找不到记录,它将不会失败。
最后,要在刀片中打印类名称,您将执行以下操作:
implode(',', $admission->admission_classes);
答案 1 :(得分:0)
您需要将整数值保存为json数组并执行以下代码
$integerIDs = array_map('intval', $inputs['admission_classes']);
$admission->admission_classes= json_encode($integerIDs);
public function index(Request $request){
$admissions = DB::select('SELECT a.*, GROUP_CONCAT(c.name) as classes FROM academy as a LEFT JOIN class c ON JSON_CONTAINS(a.classes, CAST(c.id as JSON), '$') WHERE a.school_id =2 GROUP BY a.id');
$admissions = $this->arrayPaginator($admissions, $request);
return view('frontend.index',compact('admissions','active_class'));
}
public function arrayPaginator($array, $request)
{
$page = Input::get('page', 1);
$perPage = 10;
$offset = ($page * $perPage) - $perPage;
return new LengthAwarePaginator(array_slice($array, $offset,
$perPage, true), count($array), $perPage, $page,
['path' => $request->url(), 'query' => $request->query()]);
}
我还没有检查代码,希望这可以帮助您继续....