【问题标题】:How do I use custom attribute on scope?如何在范围上使用自定义属性?
【发布时间】:2021-02-20 11:22:14
【问题描述】:

在 Laravel 范围内使用自定义属性

模型.php

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


public function scopeSearch($query, $search) 
{
    return $query->where('number', 'LIKE', '%' . $search . '%')
                ->orWhere('client_name', 'LIKE', '%' . $search . '%');
}

我收到一个错误SQLSTATE[42S22]: Column not found: 1054 Unknown column 'client_name' in 'where clause'

【问题讨论】:

  • 您不能在查询中使用这些属性。自定义属性在 php 应用程序中,而不是在 mysql 数据库中
  • 我还读到您不能在查询中使用属性。也许我会尝试另一种解决方案。谢谢!
  • 这能回答你的问题吗? eloquent search/where on custom attributes
  • @PouyaHeydari 我遇到了那个解决方案,但它不能解决我的问题。但我已经使用->whereHas('table', function ($query) {}) 解决了我的问题

标签: php laravel eloquent model


【解决方案1】:

尝试添加

 ->orWhere('{table_name}.client_name', 'LIKE', '%' . $search . '%');

如果您要加入,它会有所帮助。

【讨论】:

  • 我正在使用雄辩的关系,但我尝试了你的建议,它似乎不适用于我的结构:) 我不知道如何使用我在范围或 where 子句中创建的属性Table::where('number', 'LIKE', '%' . $request->search . '%')->orWhere('client_name', 'LIKE', '%' . $request->search . '%')
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-06-27
  • 1970-01-01
  • 2014-09-21
  • 2015-03-18
  • 2015-07-07
  • 1970-01-01
相关资源
最近更新 更多