當用戶不是管理員時遇到問題。目標是僅獲取屬於該用戶的請求,但是當我使用where
子句時,我會從數據庫中獲取所有請求。 它應該只能得到所有請求管理員。Laravel與關係中的問題
謝謝你的幫助!
public function index(){
$status = request('status', -1);
$paper_size = request('paper_size', -1);
if (auth()->user()->isAdmin()) {
$requests = Request::
where('paper_size', $paper_size)->orWhereRaw($paper_size. ' = -1')->
where('status', $status)->orWhereRaw($status. ' = -1')->
orderBy(
request('orderby') ? request('orderby') : 'created_at',
request('order') ? request('order') : 'DESC'
)->paginate(10);
$departments = Departament::All();
return view('Requests.index', compact('requests', 'departments'));
}
$requests = auth()->user()->requests()->
where('status', $status)->orWhereRaw($status. ' = -1')->
where('paper_size', $paper_size)->orWhereRaw($paper_size. ' = -1')->
orderBy(
request('orderby') ? request('orderby') : 'created_at',
request('order') ? request('order') : 'DESC'
)->paginate(10);
return view('Requests.index', compact('requests'));
}
UPDATE:
我已經可以列出所有的用戶請求,但是狀態過濾器不起作用。
PS:過濾器 「PAPER_SIZE」 正按預期
解決:
由於整個社會,特別是對@Sandeesh
public function index(){
request('status') == -1 || request('status') == null ?
$statusExists = false : $statusExists = true;
$status = request('status');
request('paper_size') == -1 || request('paper_size') == null ?
$paper_sizeExists = false : $paper_sizeExists = true;
$paper_size = request('paper_size');
$is_admin = auth()->user()->isAdmin();
$requests = Request::when($statusExists, function ($query) use ($status) {
return $query->where('status', $status);
})
->when($paper_sizeExists, function ($query) use ($paper_size) {
return $query->where('paper_size', $paper_size);
})
->when(!$is_admin, function ($query) {
return $query->where('owner_id', auth()->id());
})
->orderBy(request('orderby', 'created_at'), request('order', 'desc'))
->paginate(10);
if (!$is_admin) {
return view('Requests.index', compact('requests'));
}
$departments = Departament::all();
return view('Requests.index', compact('requests', 'departments'));
}
首先,刪除該圖片並粘貼代碼,然後選擇代碼並按下圖標縮進代碼。然後,刪除網頁標籤,因爲您只需要SQL和Laravel的幫助。 – matiaslauriti
完成,感謝您的提示 – BLDD
建立一個名爲Request的模型類可能不是一個好主意。這也是[HTTP請求類]的名稱(https://laravel.com/docs/5.4/requests)。 – aynber