簡體   English   中英

將where條件應用於多態關系laravel 8中的相關模型

[英]Apply where condition to related models in polymorphic relation laravel 8

我在多態關系中面臨一個問題,我無法使 whereHas 起作用。 關系代碼可以很好地返回相關模型,但是需要將 where 條件應用於與多態關系連接的模型的關系嗎?

我的多態關系是由兩個模型映射的。 例如:Events 和 Meetings 兩個模型都有自己的關系來存儲他們的受讓人(屬於許多人)我需要將 where 條件應用於受讓人關系以獲取所需的數據,在我的多態關系中,我與受讓人獲得了數據,但不是與條件適用。

class MainEvant extends Model
{
     public function eventheadable()    
         {  
          return $this->morphTo('eventhead', 'event_type_id', 'event_id')
           ->morphWith([ Events::class=>['assignee'],             
                     Meeting::class=>['assignee'], ]); 
              }

}

我最近也遇到了類似的問題,我是這樣解決的,不確定代碼質量

在您的控制器中,

 MainEvant::with('eventheadable')->whereHasMorph('eventheadable',Events::class,function ($query)  {
                $query->whereHas('assignee', function ($q)  {
                    $q->where(); // Your Condition
                });
            })->orwhereHasMorph('eventheadable',  Meeting::class,function ($query) {
                $query->whereHas('assignee', function ($q)   {
                    $q->where(); // Your Condition
                });
            })->get();

也可以在官方文檔中查看,

文檔: https : //laravel.com/docs/8.x/eloquent-relationships#querying-morph-to-relationships

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM