douzhoubing2805 2018-10-08 17:31
浏览 120

Laravel模型之间的关系

I'm trying to refactor my project from having all code under the App folder into seperate composer packages. However I've hit a blocker which I could use some input to solve:

To simplify I'd like to create 2 packages, Core and Customers. I want Core to be fully seperated, having no references to any of my other packages. Inside Core there is a model called Business, and in Customer there is a model called Customer. There is a many-to-one relation ship between the models. The problem arises when I want to create the Eloquent relationship methods. Customer is dependant on Core, so this is not an issue, $this->belongsTo(Business::class). However, to get the inverse Core needs to know about the Customer model, $this->hasMany(Customer::class).

Is there a way around this? Like maybe registering a method on the Business model from my Customer package? Or have I gotten it all backwards?

EDIT

For those not familiar with Laravel, a relationship is defined as a function in the model class

class Business extends Model {
   public function customers() {
       return $this->hasMany(Customer::class);
   }
}
  • 写回答

2条回答 默认 最新

  • douzhuoxia0587 2018-10-08 18:38
    关注

    How most people do this is dependency injection, but that's more of a service type thing and less of a model relationship type thing. As you have it now I can think of a couple options.

    1. Move the Business class out of core or customers into core. This depends on just how "core" these models are to your applications.
    2. Dependency inject your relationship using an enum or registry

         class Business extends Model {
             public function customers() {
                 return $this->hasMany(ModelEnum::byName('Customers')->class());
             }
         }
      

    or

     class Business extends Model {
           public function customers() {
               $models = collect(get_declared_classes())->filter(function ($item) {
                   $item == 'YOURPACKAGENAME\Models\\Customers' ? $item : throw new Exception();
    
                   return $item
               });
    
               return $this->hasMany($item);
           }
        }
    

    I think the best thing though would be to either add or remove the class(es), Having an intra package model kinda defeats the purpose of seperating you code with packages.

    评论

报告相同问题?

悬赏问题

  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染