如何在Laravel模型中创建动态字段

时间:2019-12-17 17:08:35

标签: php laravel laravel-5

我需要在其他模型中的模型中动态创建一些字段,例如,我有一个模型到属性表,而另一个模型有属性规则,那么如何将属性规则与属性表结合在一起。其他带有代码的示例

 class Properties extends Model{
   protected $table = 'properties';
 }

 class PropertyRules extends Model{
   protected $table = 'properties_rules'
 }


  $properties = Properties::all();
  //i hope something like that

  $properties = [
     'id'=>1234,
     'name'=>'Property Name',
     'checkIn'=>'10:00',//come from propertiesRules
     'checkOut'=>'14:00',//come from propertiesRules
  ];

我不想为此使用外键,因为属性表中的这些字段我不会加入

1 个答案:

答案 0 :(得分:0)

您不一定需要实际的外键,但需要链接两个表的方式,并且需要定义模型之间的关系。

然后您可以实现类似于

的功能
$properties = App\Properties::with('PropertyRules')->get();

请阅读:https://laravel.com/docs/6.x/eloquent-relationships