【问题标题】:Laravel Model is a scope of tableLaravel 模型是表的范围
【发布时间】:2020-10-15 22:23:54
【问题描述】:

如何在 Laravel 中创建自定义模型,其中 Manager 是用户表的范围,其中 is_manager = 1 ? 我觉得把不同的模型User和Manager做起来比较清楚,可以吗?

【问题讨论】:

  • 您希望对 User 模型的查询包括经理和普通用户,还是普通用户?
  • 只是经理好

标签: php laravel eloquent


【解决方案1】:

创建a global scope class 喜欢:

<?php

namespace App\Models\Scopes;

use App\Models\Hotels\AbstractHotelImage;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;

class IsManagerScope implements Scope
{
    /**
     * Apply the scope to a given Eloquent query builder.
     *
     * @param Builder $builder
     * @param Model   $model
     * @return void
     */
    public function apply(Builder $builder, Model $model): void
    {
        $builder->where('is_manager ', 1);

    }
}

然后创建您的管理器模型,使其扩展您的用户模型并在其booted 方法中应用全局范围:

<?php

namespace App\Models;

use App\Models\Scopes\IsManagerScope;

class Manager extends User
{

    /**
     * The "booted" method of the model.
     *
     * @return void
     */
    protected static function booted(): void
    {
        static::addGlobalScope(new IsManagerScope);
    }

}

您也可以使用Anonymous Global Scope 在模型中内联执行此操作,这基本上是相同的,只是范围不在单独的类中。

【讨论】:

  • 谢谢我去试试
猜你喜欢
  • 2017-11-16
  • 1970-01-01
  • 2016-07-17
  • 2019-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-05
  • 2021-10-15
相关资源
最近更新 更多