我的问题有三个表:“评论”,“用户” &“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();