duanliao5995 2017-08-11 04:49
浏览 84

Laravel - 多表的单一模型

I want to use a single Model file for multiple tables.

Why???

The Table structure of all the tables is same

I have few columns to be stored as JSON Arrays and I would like to use Laravel's built in Json Serialization rather than manually serializing Arrays.

I have already read on laracast blog that it's not possible in Laravel but is there any other way to make it possible.

Thanks in advance!!!

  • 写回答

1条回答 默认 最新

  • duanjie9630 2017-08-11 06:44
    关注

    You can just create a base model that has the logic that is common to all the models, and then create your individual models that inherit from the base model.

    class Auto extends Model
    {
        protected $casts = [
            'details' => 'json',
        ];
    
        public function getWheelsAttribute()
        {
            return $this->details->wheels;
        }
    }
    
    class Car extends Auto
    {
        // models your "cars" table
    }
    
    class Truck extends Auto
    {
        // models your "trucks" table
    }
    
    class Bus extends Auto
    {
        // models your "buses" table
    }
    

    Or, you could create a trait with the common functionality and use the trait in all your child models.

    trait HasJsonDetails
    {
        protected $casts = [
            'details' => 'json',
        ];
    
        public function getWheelsAttribute()
        {
            return $this->details->wheels;
        }
    }
    
    class Car extends Auto
    {
        // models your "cars" table
    
        use HasJsonDetails;
    }
    
    class Truck extends Auto
    {
        // models your "trucks" table
    
        use HasJsonDetails;
    }
    
    class Bus extends Auto
    {
        // models your "buses" table
    
        use HasJsonDetails;
    }
    

    Or, another option, if the table structure truly is and will always be the same, would be to combine all your tables into one table and use single table inheritance to have multiple models all use the same table.

    With this method, you would add a type field to your table to tell you which class to use to model the individual row. It also requires some customization, but you can find an STI package to use, or follow this forum thread for more information:

    https://laravel.io/forum/02-17-2014-eloquent-single-table-inheritance

    This, of course, would still need to be combined with one of the methods mentioned above to share implementation logic across the multiple models.

    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题