Php 具有多个表的Laravel搜索数据库
我有一个名为Php 具有多个表的Laravel搜索数据库,php,laravel,search,orm,eloquent,Php,Laravel,Search,Orm,Eloquent,我有一个名为records的表,其中有一个user\u id列,该列链接到users表以设置所有权 我可以使用搜索字符串通过title正确筛选记录: $records->where('title', 'LIKE', '%'.$search.'%'); 但我还想返回包含users.firstname和users.lastname的结果,这是我(糟糕的)加入尝试: $records->join('users', 'users.id', '=', 'records.user_id')
records
的表,其中有一个user\u id
列,该列链接到users
表以设置所有权
我可以使用搜索字符串通过title
正确筛选记录:
$records->where('title', 'LIKE', '%'.$search.'%');
但我还想返回包含users.firstname
和users.lastname
的结果,这是我(糟糕的)加入尝试:
$records->join('users', 'users.id', '=', 'records.user_id')
->where('users.firstname', 'LIKE', '%'.$search.'%')
->orWhere('users.lastname', 'LIKE', '%'.$search.'%')
->orWhere('title', 'LIKE', '%'.$search.'%');
// SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in order clause is ambiguous
您需要设置在内部查询中也使用搜索参数:
$records->join('users', function($join) use ($search)
{
$join->on('users.id', '=', 'records.user_id')
->where('users.firstname', 'LIKE', '%'.$search.'%')
->orWhere('users.lastname', 'LIKE', '%'.$search.'%');
});
在等待更好的答案时,我找到了一个可行的解决方案,但它不是最优的,因为它需要一个额外的查询来收集作者
用户id
,然后使用它来查询记录
// Get the author ID
$author = DB::table('users')
->select(DB::raw('CONCAT_WS(" ",`firstname`,`lastname`) as `fullname`,id'))
->having('fullname', 'LIKE', '%'.$search.'%')
->first();
// $author output:
stdClass Object
(
[fullname] => John Doe
[id] => 35
)
// Query the records using the gathered ID
$records->where('user_id', $author->id)
->orWhere('title', 'LIKE', '%'.$search.'%');
此解决方案的问题:除了额外的查询外,如果有人搜索John Doe
或某个标题
,结果是正确的。但是,如果搜索John Doe Some Title,则不会显示任何内容,因为找不到作者和标题。如果我知道您希望通过使用$search进行筛选从记录返回结果,并且还希望显示此记录的用户信息。
你可以用。
您的型号必须是:
在用户模型中:
public function records()
{
return $this->hasMany(Record::class);
}
在记录模型中:
public function user()
{
return $this->belongsTo(User::class);
}
在控制器中:
Record::where('title', 'LIKE', '%'.$search.'%')
->with('user')
->first();
谢谢,但是我去掉了不必要的代码来保持它的整洁。我将更新示例以避免混淆。我希望返回搜索查询John Doe
的所有记录,但是firstname
和lastname
在用户
表中,而不是记录
表中。此外,我还想返回John Doe Some Title
的记录,其中John Doe
位于users
表中,而Some Title
位于records
表中。