分享 . 快乐
i'm currently using this code in my own project
my Model (\App\Production\Models\Production 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
\App\Production\Models\Production::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 \App\Production\Models\Production model have 'panen_future_date' filed in its table.
posted on 2019-06-06 11:42 刘应杰 阅读(493) 评论(0) 编辑 收藏 举报
ghost commented on Apr 13, 2017 •
i'm currently using this code in my own project
my Model (\App\Production\Models\Production Model)
my Controller
and it works for my use case.
please note that all model related to \App\Production\Models\Production model have 'panen_future_date' filed in its table.