Laravel 与附加 where 语句的关系

问题描述

我知道我可以通过以下方式定义关系

Class Users extends Model{
   
   function profile(){
      return $this->hasOne(Profile::Class);
   }
}

有没有办法像除了可定义的外键和本地键之外的关系添加额外的查询,我只想获取那些字段 active 包含值 { {1}}。配置文件模型有一个名为 active 的字段。非常感谢任何帮助和想法,在此先感谢您。

解决方法

你可以试试

return $this->hasOne(Profile::Class)->where('active',1);

但更好的方法是像这样使用 Scope。

  1. 创建一个文件夹 app/Scopes 并添加一个新文件 ActiveUserOnly.php

  2. 把这段代码放在那里

    namespace App\Scopes;
    
    use \Illuminate\Database\Eloquent\Builder;
    use \Illuminate\Database\Eloquent\Scope;
    use \Illuminate\Database\Eloquent\Model;
    
    class ActiveUsersOnly implements Scope {
        /**
         * @inheritdoc
         *
         * @param Builder $builder
         * @param Model $model
         *
         * @return Builder|void
         */
        public function apply( Builder $builder,Model $model ) {
            return $builder->where( 'active','=',true );
        }
    }
    
  3. 将此代码添加到 Profile 模型的顶部。

     use App\Scopes\ActiveProfilesOnly;
    

将此代码添加到您的个人资料模型中。

    protected static function boot() {
        parent::boot();
        static::addGlobalScope( new ActiveProfilesOnly() );
    }
  1. 那么此代码将在您的用户模型中工作。

     Class Users extends Model{
    
        function profile(){
           return $this->hasOne(Profile::Class);
    
    
         }
     }