【问题标题】:How to search if relationship exists?如何搜索是否存在关系?
【发布时间】:2018-01-25 07:25:08
【问题描述】:

我使用 Algolia 作为我的搜索驱动程序,我只是尝试根据他们是否有关系这一事实来搜索我的用户记录。

App\User::has('restaurant')->search('Chris')->get(); 

我使用 Laravel Scount 并想搜索所有拥有餐厅的用户然后列出它们,但我收到的错误是

带有消息“调用未定义方法”的 BadMethodCallException Illuminate\Database\Query\Builder::search()'

如何根据关系进行搜索?

【问题讨论】:

  • 你想获取名字为Chris的用户吗?
  • 搜索比给定的示例更广泛,所以我想根据关系是否明显来使用 search()。这种关系也在 Algolia 中被索引
  • @Chris 显示您的用户和餐厅模型
  • 对于刚刚被他/她的灵魂伴侣抛弃的心来说,这个问题的标题很难阅读。
  • 你有可搜索的包或特征吗??

标签: php laravel algolia laravel-scout


【解决方案1】:

最好的方法是在发送到 Algolia 的数据中添加餐厅 int 属性,这样您就可以依赖“where”属性。我不知道您的数据是什么样的,因此代码可能需要一些修改。

其中非常有限,只能对整数进行相等操作:https://laravel.com/docs/scout#where-clauses

方案一:使用where方法

首先,覆盖toSearchableArray 方法,使其具有如下内容:

public function toSearchableArray()
{
    $record = $this->toArray();

    $record['has_resturant'] = (int) !empty($this->restaurants);

    return $record;
}

使用命令 php artisan scout:import "App\User" 重新索引所有内容

解决方案 2:Algolia 宏包

将此包添加到您的项目中:https://github.com/algolia/laravel-scout-algolia-macros

创建restaurant_count 属性

public function toSearchableArray()
{
    $record = $this->toArray();

    $record['resturant_count'] = count($this->restaurants);

    return $record;
}

重新索引。

这样搜索:

User::search('Chris')->with('filters' => 'restaurant_count>0')->get();

如果这对你有用,请告诉我。

【讨论】:

  • 伟大的想法。谢谢!
【解决方案2】:

这通常在模型缺乏特征时发生

将特征添加到模型,您希望搜索功能可用您还需要通过 $searchable 属性指定搜索规则(您要运行搜索的列)。

class User extends Authenticatable
{
   use SearchableTrait;
   .
   .
   .
}

在那个控制器函数中:

 App\User::search('chris')->with('restaurant')->get();

这将返回用户与 chris 加入餐厅

【讨论】:

  • 不起作用。带有消息“方法不存在”的 BadMethodCallException。
【解决方案3】:

使用first() 而不是get() 使其工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-04
    • 2019-03-25
    相关资源
    最近更新 更多