zoukankan      html  css  js  c++  java
  • Laravel 多态关联中不能使用 has, whereHas

    edited by ghost 

    i'm currently using this code in my own project

    my Model (AppProductionModelsProduction Model)

    public function detail()
    {
        return $this->morphTo('detail');
    }
    
    public function scopeDetailable($query, $callable = null)
    {
        list($type, $key) = $this->getPolymorphicFields();
    
        $this->newQuery()->distinct()->get([$type])->keyBy($type)->map(function ($model)  use ($type) {
            return (new $model->{$type})->getTable();
        })->each(function ($table, $modelClass) use (&$query, $key, $callable) {
            $model = new $modelClass;
    
            $query = $query->orWhereExists(function ($query) use ($table, $model, $key, $callable) {
                $query->select('*')->from($table)->whereRaw("{$this->getTable()}.{$key} = {$table}.{$model->getKeyName()}")
                    ->when($callable instanceof Closure, $callable);
            });
        });
    
        return $query;
    }
    
    protected function getPolymorphicFields()
    {
        $relation = $this->detail();
    
        return [$relation->getMorphType(), $relation->getForeignKey()];
    }
    

    my Controller

    AppProductionModelsProduction::detailable(function ($query) {
        $query->whereDate('panen_future_date', '2017-02-08');
    })->with('detail')->get()
    

    and it works for my use case.

    please note that all model related to AppProductionModelsProduction model have 'panen_future_date' filed in its table.

     
     
  • 相关阅读:
    冒泡算法
    Eclipse 安装插件(aptana、svn 、git、Java EE、JSHint)
    smtp和pop3
    EJB 3.0 + JBOSS 5.1
    有状态EJBBean和无状态的EJBBean
    EJB3.0在发布时出现异常javax.naming.NameNotFoundException: myqueue not bound
    Django之路由系统
    Mysql安装与连接
    Django之Form组件
    jinja2模板
  • 原文地址:https://www.cnblogs.com/mouseleo/p/10984076.html
Copyright © 2011-2022 走看看