如何搜索关系是否存在?
How to search if relationship exists?
我正在使用 Algolia 作为我的搜索驱动程序,我只是想根据他们是否有关系这一事实来搜索我的用户记录。
App\User::has('restaurant')->search('Chris')->get();
我使用 Laravel Scount 并想搜索所有拥有餐厅的用户,然后列出它们,但我收到的错误是
BadMethodCallException with message 'Call to undefined method
Illuminate\Database\Query\Builder::search()'
如何根据关系进行搜索?
这通常发生在模型缺乏特征时
将特征添加到模型中,您希望搜索功能可用您还需要通过 $searchable [= 指定搜索规则(您想要 运行 搜索的列) 21=].
class User extends Authenticatable
{
use SearchableTrait;
.
.
.
}
并在该控制器函数中:
App\User::search('chris')->with('restaurant')->get();
这个 returns 用户和 chris 一起加入了餐厅
使用 first()
而不是 get()
使其工作。
最好的方法是在发送到 Algolia 的数据中添加 restaurant int 属性,这样您就可以依赖 "where" 属性。我不知道你的数据是什么样的,所以代码可能需要一些修改。
where非常有限,只能with with equal operations on ints: https://laravel.com/docs/scout#where-clauses
解决方案 1:使用 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();
如果这对你有用,请告诉我。
我正在使用 Algolia 作为我的搜索驱动程序,我只是想根据他们是否有关系这一事实来搜索我的用户记录。
App\User::has('restaurant')->search('Chris')->get();
我使用 Laravel Scount 并想搜索所有拥有餐厅的用户,然后列出它们,但我收到的错误是
BadMethodCallException with message 'Call to undefined method Illuminate\Database\Query\Builder::search()'
如何根据关系进行搜索?
这通常发生在模型缺乏特征时
将特征添加到模型中,您希望搜索功能可用您还需要通过 $searchable [= 指定搜索规则(您想要 运行 搜索的列) 21=].
class User extends Authenticatable
{
use SearchableTrait;
.
.
.
}
并在该控制器函数中:
App\User::search('chris')->with('restaurant')->get();
这个 returns 用户和 chris 一起加入了餐厅
使用 first()
而不是 get()
使其工作。
最好的方法是在发送到 Algolia 的数据中添加 restaurant int 属性,这样您就可以依赖 "where" 属性。我不知道你的数据是什么样的,所以代码可能需要一些修改。
where非常有限,只能with with equal operations on ints: https://laravel.com/docs/scout#where-clauses
解决方案 1:使用 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();
如果这对你有用,请告诉我。