如何使用belongssto laravel进行搜索?

时间:2017-04-23 06:01:34

标签: php laravel search laravel-5.3 laravel-eloquent

我在商店列表中搜索用户名的查询如下:

$data = Store::join('users AS b', 'b.id', '=', 'stores.user_id')
             ->where('b.name', 'like', '%hazard%')
             ->paginate();

有效。但我使用join来做到这一点。

我怎样才能使用belongsto?

我的商店模特是这样的:

class Store extends Model
{   
    protected $fillable = ['name', 'user_id', ...];
    public function user()
    {
        return $this->belongsTo(User::class,'user_id', 'id');
    }
    ...
}

2 个答案:

答案 0 :(得分:2)

使用whereHas()

try
{
    await db.SaveChangesAsync();
}
catch (Exception)
{
    try
    {
        // TODO: add to the audit here, also in a try/catch as this might fail as well
    }
    catch
    {
    }

    // rethrow the original exception
    throw;
}

答案 1 :(得分:0)

您可以使用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();