Laravel 与附加 where 语句的关系

Laravel relationship with additional where statement

我知道我可以通过

来定义关系
Class Users extends Model{
   
   function profile(){
      return $this->hasOne(Profile::Class);
   }
}

有没有一种方法可以像外键和本地键以外的关系添加额外的查询来定义,我只想获取 Profile 模型的那些字段 active 包含值的记录1 个。配置文件模型有一个名为 active 的字段。非常感谢任何帮助和想法,提前致谢。

你可以试试

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

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

  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. 将此代码添加到配置文件模型的顶部。

     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);
    
    
         }
     }