Laravel 模型 - 仅对一列 = 特定值的记录进行 CRUD?
Laravel model - CRUD only with records where one column = certain value?
假设我有一个 laravel 模型可以与某个 (MySQL) 数据库一起工作 table。
在此 table 中有一个名为 'administration' 的列。 (示例:可以是 1、2 或 3)
目前在我的控制器中,我正在使用带有 eloquent 的模式,在我的 eloquent 语句中,我只要求使用具有管理 2 的记录(crud 样式)。
我认为应该可以将 'where administration = x' 添加到我的模型而不是我的控制器,这样如果我在我的控制器中使用该模型,我将只处理具有该管理集的记录。
这可能吗?我试过用谷歌搜索,但还没有找到答案。
Laravel 为此使用 global scopes。
您将为管理创建一个范围:
<?php
namespace App\Scopes;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
class AdministrationScope implements Scope
{
/**
* Apply the scope to a given Eloquent query builder.
*
* @param \Illuminate\Database\Eloquent\Builder $builder
* @param \Illuminate\Database\Eloquent\Model $model
* @return void
*/
public function apply(Builder $builder, Model $model)
{
$builder->where('administration', '=', 2);
}
}
然后将其作为全局范围添加到模型中
<?php
namespace App\Models;
use App\Scopes\AdministrationScope;
use Illuminate\Database\Eloquent\Model;
class YourModel extends Model
{
/**
* The "booted" method of the model.
*
* @return void
*/
protected static function booted()
{
static::addGlobalScope(new AdministrationScope);
}
}
假设我有一个 laravel 模型可以与某个 (MySQL) 数据库一起工作 table。
在此 table 中有一个名为 'administration' 的列。 (示例:可以是 1、2 或 3)
目前在我的控制器中,我正在使用带有 eloquent 的模式,在我的 eloquent 语句中,我只要求使用具有管理 2 的记录(crud 样式)。
我认为应该可以将 'where administration = x' 添加到我的模型而不是我的控制器,这样如果我在我的控制器中使用该模型,我将只处理具有该管理集的记录。
这可能吗?我试过用谷歌搜索,但还没有找到答案。
Laravel 为此使用 global scopes。
您将为管理创建一个范围:
<?php
namespace App\Scopes;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
class AdministrationScope implements Scope
{
/**
* Apply the scope to a given Eloquent query builder.
*
* @param \Illuminate\Database\Eloquent\Builder $builder
* @param \Illuminate\Database\Eloquent\Model $model
* @return void
*/
public function apply(Builder $builder, Model $model)
{
$builder->where('administration', '=', 2);
}
}
然后将其作为全局范围添加到模型中
<?php
namespace App\Models;
use App\Scopes\AdministrationScope;
use Illuminate\Database\Eloquent\Model;
class YourModel extends Model
{
/**
* The "booted" method of the model.
*
* @return void
*/
protected static function booted()
{
static::addGlobalScope(new AdministrationScope);
}
}