[英]How can I search with belongsto laravel?
My query to search for a username in a store listing is as follows: 我在商店列表中搜索用户名的查询如下:
$data = Store::join('users AS b', 'b.id', '=', 'stores.user_id')
->where('b.name', 'like', '%hazard%')
->paginate();
It works. 有用。 But I use join to do it.
但我使用join来做到这一点。
How can I do it using belongto? 我怎么能用belongsto呢?
My store model is like this : 我的商店模型是这样的:
class Store extends Model
{
protected $fillable = ['name', 'user_id', ...];
public function user()
{
return $this->belongsTo(User::class,'user_id', 'id');
}
...
}
Use whereHas()
: 使用
whereHas()
:
Store::whereHas('user', function($q) use($username) {
$q->where('name', 'like', '%'.$username.'%');
})->paginate(5);
You can do it using Searchable package in order to search through the model fields and its relations fields 您可以使用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');
}
}
use : 使用 :
$users = User::search($query)->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.