douwa6220 2015-07-06 16:01
浏览 91
已采纳

Laravel多态关系通过动态类型

i used polimorphic relation in laravel but my problem is, how to pass relation_type dynamically (Example:When i want to create tickets for Organization pass Organization Model namespace or for Contact pass Contact Model namespace).

This is my model

class Ticket

public function relation(){
  return $this->morphTo();
}

class Organization

public function tickets(){
   return $this->morphMany('Ticket','relation');
}

class Contact

public function tickets(){
   return $this->morphMany('Ticket','relation');
}

i don't now it is possible but i want a function that accept two param

public function ticketRelation($model, $Id){
     $modelNamespace = $model::findById($id); 
     $ticket = new Ticket();
     $ticket->save();
     $modelNamespace->tickets()->save($ticket);    
}

In this casse a $model param should be accept Organization or Contact to associate new ticket And if i realize this i need only one route that accept a model and an Id to associate new ticket.How to pass an class like a param in this method ?

  • 写回答

1条回答 默认 最新

  • doulian4467 2015-07-06 16:35
    关注

    All you need to do to link a Ticket to either Organization or Contact is:

    $organization = new Organization;
    $organization->save();
    
    $contact = new Contact();
    $contact->save();
    
    $organizationTicket = new Ticket;
    $organizationTicket->relation()->associate($organization);
    $organizationTicket->save();
    
    $contactTicket = new Ticket;
    $contactTicket ->relation()->associate($contact);
    $contactTicket ->save();
    

    Yes, it is possible to achieve what you want with your function.

    Since PHP 5.3 it is possible to dynamically call class static methods on a variable containing class name, so if $model contains a valid namespaced class name you can just do:

    public function ticketRelation($class, $id){
         $model= $class::findOrFail($id); 
         $ticket = new Ticket();
         $ticket->relation()->associate($model);
         $ticket->save();
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?