动态表和模型在Laravel 5 [英] Dynamic tables and models in Laravel 5

查看:102
本文介绍了动态表和模型在Laravel 5的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下表:

 
id
title
.. 。

dynamic_table_1_infos
id
page_id
image_id
dynamic_field_1
dynamic_field_2
...

dynamic_table_2_infos
...

所以有一对多的关系。 >

有没有办法使用一般的方法,而不会为每个表创建一个DynamicTable [No]信息模型



如果我在这些模型中需要一些额外的方法怎么办?



Page模型将与dynamic_table_ [no] _infos表有许多关系。所以我可能需要一个这样做的一般方法。
(有很多dynamic_table_1_infos /有很多dynamic_table_2_infos ...)



我想要做的是某种灵感来自Dupal的内容类型。 >

解决方案

如果要根据某些model属性的值将单个模型数据保存到多个表中,则需要覆盖模型的 getTable()方法返回应该写入的表的名称。



我不知道你想如何决定哪个如果您的模式中有一个名为细分的属性,您可以执行以下操作:

  public function getTable(){
return'dynamic_table_'。 $ this->细分。 _infos’;
}


I have the next tables:

pages
    id
    title
    ...

dynamic_table_1_infos
    id
    page_id
    image_id
    dynamic_field_1
    dynamic_field_2
    ...

dynamic_table_2_infos
...

So there are "one to many" relationships.

Is there any way to use a general approach without creating a DynamicTable[No]Info model "on the fly" for each table?

And what if I will need some extra methods in these models?

The "Page" model will have many relationships with "dynamic_table_[no]_infos" tables. So I will probably need a general method for doing this. (Has many dynamic_table_1_infos / has many dynamic_table_2_infos ...)

What I am trying to do is somehow inspired by Dupal`s content types.

解决方案

If you want to save a single model data to multiple tables depending on the value of some model attribute, you'll need to override model's getTable() method to return the name of the table it should write to.

I'm not sure how you want to decide to which table Eloquent should save to - for example, if you had an attribute called segment in your mode, you could just do:

public function getTable() {
  return 'dynamic_table_' . $this->segment . '_infos';
}

这篇关于动态表和模型在Laravel 5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆