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 聚类分析或者python进行数据分析
  • ¥15 如何用visual studio code实现html页面
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?