简体   繁体   English

在雄辩的ORM中向模型添加字段

[英]Adding fields to a model in Eloquent ORM

I'm using Eloquent in a project, basically I have a Author model, that has name, email, etc. 我在一个项目中使用Eloquent,基本上我有一个Author模型,该模型具有名称,电子邮件等。

I have $author->created_at, and $author->name, etc. 我有$author->created_at,$author->name,等。

What I want, is more fields in the object that are always there, for example: $author->created_at_formatted, which would basically be date(format, created_at) 我想要的是对象中始终存在的更多字段,例如: $author->created_at_formatted,基本上是日期(格式,created_at)

Any ideas or tips on how I can do this within the class? 关于如何在课堂上做到这一点的任何想法或提示? Thanks. 谢谢。

The model itself should not be responsible for making the data "pretty" for things like views. 模型本身不应该负责使诸如视图之类的数据“漂亮”。 Many people would opt to do this in the controller or even the view. 许多人会选择在控制器甚至视图中执行此操作。 I recommend you look into "presenters" and how they are used to transform and manipulate the data for views. 我建议您研究“演示者”,以及如何使用它们来转换和处理视图数据。

There are existing presenter packages available for Laravel 4 which you can start using right away (and I recommend that you do). Laravel 4有可用的演示程序包 ,您可以立即使用(我建议您使用)。

I don't know if there is a way to create your own automatically populated columns, but if a "created_at_formatted" column is all you need, you can just add the following to your model to change the format of the created_at and updated_at columns: 我不知道是否可以创建自己的自动填充的列,但是如果只需要一个“ created_at_formatted”列,则可以将以下内容添加到模型中,以更改created_at和updated_at列的格式:

public function freshTimestamp()
{
    // Your custom timestamp format
    return date("Y-m-d H:i:s");
}

You need to understand how eloquent works and what its main purpose is. 您需要了解口才如何发挥作用,其主要目的是什么。

It is simply just a way to easily interact with a database table through an object (It is an Object-relational mapper ie it maps a relational database table to an object) 这只是通过对象轻松与数据库表进行交互的一种方式(这是一个对象关系映射器,即它将关系数据库表映射到对象)

If you want it to have another field, you would have to add that field to your database table. 如果希望它具有另一个字段,则必须将该字段添加到数据库表中。

If however that other field is part of ANOTHER table, you can use the join() query method. 但是,如果该其他字段是ANOTHER表的一部分,则可以使用join()查询方法。 The fields from both tables will be added. 两个表中的字段都将添加。 If for whatever reason you cannot modify your author table, you could create another table with the fields you want and then do a join. 如果出于某种原因无法修改作者表,则可以使用所需的字段创建另一个表,然后进行联接。

If you want more help doing a join, let me know and I'll add the code here. 如果您希望获得更多帮助,请告诉我,我将在此处添加代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM