这是我想要执行的,但它不起作用:
$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,如果准备好的语句像在第一个示例中那样为我处理它,我更喜欢它。
知道如何解决这个问题吗?
答案 0 :(得分:5)
使用 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
----
],
答案 1 :(得分:0)
对于此类信息,如果您想从数据库中获取。 你可以使用访问器
public function getFullNameAttribute()
{
return $this->first_name.' '.$this->last_name);
}
用法:
$user = User::find(1);
echo $user->full_name;