如果我写自定义一个wherehasin在model里面
时间: 2024-03-10 22:46:09 浏览: 20
如果你想在 Laravel 模型中自定义一个 `wherehasin` 方法,可以按照以下步骤进行:
1. 在模型中定义一个 `whereHasIn` 方法,该方法应该接收三个参数:关联关系名称、关联模型的字段名和需要匹配的值数组。方法内部通过 `$this->newQuery()` 创建一个新的查询构建器实例,然后通过 `$query->whereIn()` 方法将查询限制为符合条件的主模型记录。
```php
public function whereHasIn($relation, $column, array $values)
{
$this->loadMissing($relation);
$related = $this->$relation()->getRelated();
$relatedKeyName = $related->getKeyName();
$query = $related->newQuery();
$query->whereIn($column, $values);
$this->query->whereIn($this->getTable().'.'.$this->getKeyName(), function ($query) use ($related, $relatedKeyName, $column) {
$query->select($relatedKeyName)
->from($related->getTable())
->whereColumn($related->getTable().'.'.$relatedKeyName, $this->getTable().'.'.$related->getForeignKey())
->where($column, $this->getQuery()->getBindings()[0]);
});
return $this;
}
```
2. 在模型中注册 `whereHasIn` 方法名为一个本地作用域,以便在其他查询中使用。
```php
protected static function boot()
{
parent::boot();
static::addGlobalScope('whereHasIn', function ($query) {
$model = $query->getModel();
$query->macro('whereHasIn', function ($relation, $column, array $values) use ($model) {
return $model->whereHasIn($relation, $column, $values);
});
});
}
```
现在你就可以在模型中使用自定义的 `whereHasIn` 方法了。例如:
```php
$users = User::whereHasIn('posts', 'category_id', [1, 2, 3])->get();
```