我在資料庫中有一個用戶有一些客戶端的分類,它們通過 user_id 連接。在我看來,表格顯示在儀表板中,只有當前登錄用戶注冊的客戶,但是當我按姓名或姓氏或郵件搜索表格時,我會看到其他用戶的客戶。這是代碼?
public function render()
{
$user = Auth::user()->id;
if($this->searchTerm == ''){
return view('livewire.dashboard.user-management', [
'clients' => Client::where('user_id', '=', $user)->orderBy($this->sortField, $this->sortAsc)->paginate(8)
]);
}
else{
return view('livewire.dashboard.user-management', [
'clients' => Client::where('user_id', '=', $user)
->where('name', 'LIKE', '%'.$this->searchTerm.'%')
->orWhere('surname', 'LIKE', '%'.$this->searchTerm.'%')
->orWhere('email', 'LIKE', '%'.$this->searchTerm.'%')
->orderBy($this->sortField, $this->sortAsc)->paginate(8)
]);
}
}
我該如何解決?
uj5u.com熱心網友回復:
您正在混合您的和/或子句。您想確保user_id始終尊重這一點,但其余的都是可能的。要解決這個問題,請將or子句傳遞到閉包中:
return view('livewire.dashboard.user-management', [
'clients' => Client::where('user_id', '=', $user)
->where(function($query) {
$query->where('name', 'LIKE', '%'.$this->searchTerm.'%')
->orWhere('surname', 'LIKE', '%'.$this->searchTerm.'%')
->orWhere('email', 'LIKE', '%'.$this->searchTerm.'%');
})
->orderBy($this->sortField, $this->sortAsc)->paginate(8)
]);
uj5u.com熱心網友回復:
您應該使用 Eloquent 關系來避免手動搜索表中的外鍵。您還可以使用僅在需要時進行搜索來創建條件查詢when(),盡管這并不是必需的 - 搜索 '%%' 無論如何都會回傳所有行。
public function render()
{
$clients = Auth::user()
->clients()
->when($this->searchTerm !== '', function ($q) {
$q->where('name', 'LIKE', '%' . $this->searchTerm . '%')
->orWhere('surname', 'LIKE', '%' . $this->searchTerm . '%')
->orWhere('email', 'LIKE', '%' . $this->searchTerm . '%')
})
->orderBy($this->sortField, $this->sortAsc)
->paginate(8)
return view('livewire.dashboard.user-management', compact('clients'));
}
User這假設和Client模型之間存在一對多的關系:
class User extends Authenticatable {
public function clients() {
return $this->hasMany(Client::class);
}
}
class Client extends Model {
public function user() {
return $this->belongsTo(User::class);
}
}
哦,永遠不要使用松散的相等運算子==;總是使用===. 它更安全,更一致。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/416426.html
標籤:
下一篇:找不到路線Laravel8
