簡體   English   中英

Laravel select 如果 id 存在於另一個表中並且列具有該表上的特定值,則所有行

[英]Laravel select all rows if id exists in another table and a column has specific values on that table

我有 4 張桌子:

通知(id、title、desc、is_published)

notices_to_districts (id, notice_id, district_id)

notices_to_employees (id, notice_id, user_id)

notices_to_establishments(id,notice_id,information_id)

我想獲得所有獨特的通知,如果,

notices_to_districts 有一個特定的 district_id,或者

notices_to_employees 有一個特定的 user_id,或者

notices_to_establishments 有一個特定的establishment_id

我在嘗試 -

$notices = Notice::join('notices_to_districts', 'notices_to_districts.notice_id', '=', 'notices.id')
            ->join('notices_to_establishments', 'notices_to_establishments.notice_id', '=', 'notices.id')
            ->join('notices_to_employees', 'notices_to_employees.notice_id', '=', 'notices.id')
            ->where('district_id', '=', $user_district_id)
            ->orWhere('establishment_id', '=', $user_establishment_id)
            ->orWhere('user_id', '=', $user_id)
            ->where('is_published', '=', 1)->get();

您應該使用閉包參數分組,否則您的“orWhere”將無法按您的意願工作。

$notices = Notice::join('notices_to_districts', 'notices_to_districts.notice_id', '=', 'notices.id')
            ->join('notices_to_establishments', 'notices_to_establishments.notice_id', '=', 'notices.id')
            ->join('notices_to_employees', 'notices_to_employees.notice_id', '=', 'notices.id')
            ->where('district_id', '=', $user_district_id)
            ->where('is_published', '=', 1)            
            ->where(
                function ($query) use ($user_establishment_id, $user_id) {
                        $query->orWhere('establishment_id', '=', $user_establishment_id)
                            ->orWhere('user_id', '=', $user_id);
                }
            )
            ->get();

像這個例子一樣, SQL 將在您的子句周圍有正確的括號。

     I solved it - 


$notice_ids_of_district = Notices_to_district::select('notice_id')->where('district_id', '=', $user_district_id)->get();
            $notice_ids_of_establishment = Notices_to_establishment::select('notice_id')->where('establishment_id', '=', $user_establishment_id)->get();
            $notice_ids_of_employee = Notices_to_employee::select('notice_id')->where('user_id', '=', $user_id)->get();

            $notices = Notice::whereIn('id', $notice_ids_of_district)
            ->orWhereIn('id', $notice_ids_of_establishment)
            ->orWhereIn('id', $notice_ids_of_employee)
            ->get(); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM