0

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

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

有没有一种方法可以向关系中添加额外的查询,比如可以定义的外键和本地键,我只想获取 Profile 模型的那些记录,该字段active包含1. 配置文件模型有一个名为 active 的字段。任何帮助,想法都非常感谢,在此先感谢您。

4

1 回答 1

0

你可以简单地尝试

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;
    

在您的 Profile 模型中添加此代码。

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

     Class Users extends Model{
    
        function profile(){
           return $this->hasOne(Profile::Class);
    
    
         }
     }
    
于 2021-03-10T01:48:27.157 回答