如何修复此查询concat查询



这是我想要执行的,但它不起作用:

$users = DB::table("users")
->select(array(
'users.*',
DB::raw("CONCAT (firstname, ' ', lastname) as fullName "),
))
->where("fullName", "like", $query)
->get();

正如预期的那样,我得到了这个错误:

Column not found: 1054 Unknown column 'fullName' in 'where clause'

有什么方法可以让where子句知道fullName吗?我知道我能做到:

$users = DB::table("users")
->select(array(
'users.*',
DB::raw("CONCAT (firstname, ' ', lastname) as fullName "),
))
->where(DB::raw("CONCAT (firstname, ' ', lastname) like ".$query))
->get();

但如果我这样做,那么我需要清理$query,我更喜欢准备好的语句像第一个例子中那样为我处理它。

知道怎么绕过这个吗?

使用having()而不是where()

$users = DB::table("users")
->select(array(
'users.*',
DB::raw("CONCAT (firstname, ' ', lastname) as fullName "),
))
->having("fullName", "like", $query)
->get();

并更改检查DB必须在严格模式下运行的配置设置:

/config/database.php中:严格执行false

'mysql' => [
----
----
'strict' => true,   // <--- Change this to false
----
],

对于这种类型的信息,如果您想从数据库中获取。您可以使用Accessor

public function getFullNameAttribute()
{
return $this->first_name.' '.$this->last_name);
}

用法:

$user = User::find(1);
echo $user->full_name;

最新更新