1

我在多态关系中面临一个问题,我无法让 whereHas 工作。关系代码可以正常返回相关模型,但是需要对与多态关系连接的模型的关系应用 where 条件?

我的多态关系是由两个模型映射的。例如:事件和会议两种模型都有自己的关系来存储他们的受让人(属于许多人)我需要将 where 条件应用于受让人关系以获取所需的数据,在我的多态关系中,我得到了与受让人的数据,但没有与适用条件。

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

}
4

1 回答 1

1

我最近也遇到了类似的问题,我是这样解决的,不知道代码质量如何

在您的控制器中,

 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

于 2021-10-13T08:10:47.900 回答