微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Laravel 与附加 where 语句的关系

如何解决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);
    
    
         }
     }
    

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。