我的問題有三個表:「評論」,「用戶」 &「company_contacts」「喜歡」上表的外鍵查詢分配給基於關係型多表
的「意見」表有兩列: "company_contact (INT)"
& "company_contact_kind (String)"
comments.company_contact
要麼分配給users.id
或company_contacts.id
基於要麼如果comments.company_contact_kind = 'contact'
或者comments.company_contact_kind = 'user'
這裏是我的查詢:
$data['comments'] = Comment::join('users', 'comments.creator_id', '=', 'users.id')
->join('users AS user_contacts', 'comments.company_contact', '=', 'user_contacts.id')
->join('company_contacts', 'company_contacts.id', '=', 'comments.company_contact')
->where('comments.commentable_type', $request->type)
->where('comments.commentable_id', $request->company_id)
->where(function($query) use ($request){
$query->orWhere('body', 'LIKE', '%' . $request->q . '%')
->orWhere('users.first_name', 'LIKE', '%' . $request->q . '%')
->orWhere('users.last_name', 'LIKE', '%' . $request->q . '%')
->orWhere('user_contacts.first_name', 'LIKE', '%' . $request->q . '%')
->orWhere('user_contacts.last_name', 'LIKE', '%' . $request->q . '%')
->orWhere('company_contacts.first_name', 'LIKE', '%' . $request->q . '%')
->orWhere('company_contacts.last_name', 'LIKE', '%' . $request->q . '%')
->orWhere('comments.contact_type', 'LIKE', '%' . $request->q . '%')
->orWhere('tags', 'LIKE', '%' . $request->q . '%');
})
->orderBy('comments.created_at', 'DESC')
->select('comments.*')
->get();
我的問題: 當搜索一個具體的意見聯繫,因爲我引用的用戶和聯繫人我查詢和都等於comments.company_contact
內,如果我搜索其中任意company_contacts.id
的名字或姓氏,它將返回users.id
作爲comments.company_contact
的結果,因爲comments.company_contact
引用用戶和company_contacts。
有沒有辦法在查詢中設置一個更直觀的條件?
解決:
多虧了@cmerriman提出的答案,我可以通過下面的查詢來調整回答和解決它:
$data['comments'] = Comment::join('users', 'comments.creator_id', '=', 'users.id')
->leftJoin('users AS user_contacts', function ($join) {
$join->where('comments.company_contact_kind', '=', 'user')
->on('comments.company_contact', '=','user_contacts.id');
})
->leftJoin('company_contacts', function ($join) {
$join->where('comments.company_contact_kind', '=', 'contact')
->on('comments.company_contact', '=','company_contacts.id');
})
->where('comments.commentable_type', $request->type)
->where('comments.commentable_id', $request->company_id)
->where(function($query) use ($request){
$query->orWhere('body', 'LIKE', '%' . $request->q . '%')
->orWhere('users.first_name', 'LIKE', '%' . $request->q . '%')
->orWhere('users.last_name', 'LIKE', '%' . $request->q . '%')
->orWhere('user_contacts.first_name', 'LIKE', '%' . $request->q . '%')
->orWhere('user_contacts.last_name', 'LIKE', '%' . $request->q . '%')
->orWhere('company_contacts.first_name', 'LIKE', '%' . $request->q . '%')
->orWhere('company_contacts.last_name', 'LIKE', '%' . $request->q . '%')
->orWhere('comments.contact_type', 'LIKE', '%' . $request->q . '%')
->orWhere('tags', 'LIKE', '%' . $request->q . '%');
})
->orderBy('comments.created_at', 'DESC')
->select('comments.*')
->get();