【问题标题】:Exclude records which does not meet condition in model in laravel在 laravel 中排除模型中不符合条件的记录
【发布时间】:2018-12-07 19:33:21
【问题描述】:

我有多个表格及其相互关联的模型,命名为:"users","posts","tags","comments"

我想从所有这些模型中排除 deactive 用户的数据,并且无论何时调用这些模型中的任何一个,都不要返回 deactive 用户

我不想在他们的控制器中使用 eloquent 或查询构建器来排除那些“用户”,我需要在模型中执行此操作,以便它适用于所有使用所述模型的地方。

posts、cmets 和 tags 与用户的关系是:

 public function user()
 {
    return  $this->belongsTo('App\Models\User', 'user_id');
 }

我在相关模型中需要这样的东西:

$instance = $this->belongsTo('App\Models\User', 'user_id');
$instance->whereIsDeactive(0);//return active users only
return $instance;

在用户模型中是这样的:

return $this->whereIsDeactive(0);

有可能吗?有没有办法做到这一点?

【问题讨论】:

标签: php laravel model conditional eager-loading


【解决方案1】:

感谢@Adam,我使用全局范围解决了这个问题。

这是IsDeactive 全局范围:

namespace App\Scopes;

use Illuminate\Database\Eloquent\Scope;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;

class IsDeactiveScope 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('is_deactive', 0);
    }
}

这是如何在用户模型中调用它:

/**
     * The "booting" method of the model.
     *
     * @return void
     */
    protected static function boot()
    {
        parent::boot();

        static::addGlobalScope(new IsDeactiveScope());
    }

我希望这个解决方案对其他人有所帮助。

【讨论】:

    猜你喜欢
    • 2016-08-10
    • 1970-01-01
    • 2018-10-27
    • 2016-06-10
    • 1970-01-01
    • 2019-06-09
    • 2023-01-01
    • 1970-01-01
    • 2013-04-28
    相关资源
    最近更新 更多