如何使用 belongsto laravel 进行搜索?
How can I search with belongsto laravel?
我在商品详情中搜索用户名的查询如下:
$data = Store::join('users AS b', 'b.id', '=', 'stores.user_id')
->where('b.name', 'like', '%hazard%')
->paginate();
有效。但是我是用join来做的。
如何使用 belongto 来实现?
我的店铺模型是这样的:
class Store extends Model
{
protected $fillable = ['name', 'user_id', ...];
public function user()
{
return $this->belongsTo(User::class,'user_id', 'id');
}
...
}
使用whereHas()
:
Store::whereHas('user', function($q) use($username) {
$q->where('name', 'like', '%'.$username.'%');
})->paginate(5);
您可以使用 Searchable 包来搜索模型字段及其关系字段
use Nicolaslopezj\Searchable\SearchableTrait;
class User extends \Eloquent
{
use SearchableTrait;
/**
* Searchable rules.
*
* @var array
*/
protected $searchable = [
/**
* Columns and their priority in search results.
* Columns with higher values are more important.
* Columns with equal values have equal importance.
*
* @var array
*/
'columns' => [
'users.first_name' => 10,
'users.last_name' => 10,
'users.bio' => 2,
'users.email' => 5,
'posts.title' => 2,
'posts.body' => 1,
],
'joins' => [
'posts' => ['users.id','posts.user_id'],
],
];
public function posts()
{
return $this->hasMany('Post');
}
}
使用:
$users = User::search($query)->get();
我在商品详情中搜索用户名的查询如下:
$data = Store::join('users AS b', 'b.id', '=', 'stores.user_id')
->where('b.name', 'like', '%hazard%')
->paginate();
有效。但是我是用join来做的。
如何使用 belongto 来实现?
我的店铺模型是这样的:
class Store extends Model
{
protected $fillable = ['name', 'user_id', ...];
public function user()
{
return $this->belongsTo(User::class,'user_id', 'id');
}
...
}
使用whereHas()
:
Store::whereHas('user', function($q) use($username) {
$q->where('name', 'like', '%'.$username.'%');
})->paginate(5);
您可以使用 Searchable 包来搜索模型字段及其关系字段
use Nicolaslopezj\Searchable\SearchableTrait;
class User extends \Eloquent
{
use SearchableTrait;
/**
* Searchable rules.
*
* @var array
*/
protected $searchable = [
/**
* Columns and their priority in search results.
* Columns with higher values are more important.
* Columns with equal values have equal importance.
*
* @var array
*/
'columns' => [
'users.first_name' => 10,
'users.last_name' => 10,
'users.bio' => 2,
'users.email' => 5,
'posts.title' => 2,
'posts.body' => 1,
],
'joins' => [
'posts' => ['users.id','posts.user_id'],
],
];
public function posts()
{
return $this->hasMany('Post');
}
}
使用:
$users = User::search($query)->get();