向 Laravel 模型查询添加计算字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38113598/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add a calculated field to Laravel model query
提问by Jonathan
I have a controller which has a query such as this one:
我有一个控制器,它有一个这样的查询:
$post = Post::find($id);
$comments = $post->comments;
Where a post has many comments and a comment belongs to one post. The comments model has an id,comment,tag field.
一个帖子有很多评论,一个评论属于一个帖子。评论模型有一个 id,comment,tag 字段。
What I want to do is that for any query such as this one, the model returns the fields id, comment, tag and tag_translated, where the latter is just a translation of the tag using the Lang facade.
我想要做的是,对于像这样的任何查询,模型返回字段 id、comment、tag 和 tag_translated,其中后者只是使用 Lang 外观的标记的翻译。
I could solve this by using a for on the controller which iterates over the $comments and adds the field, however Ill have to do that for every controller that requires the tag_translared field. Is there a way to ask the model to include such a field?
我可以通过在控制器上使用 for 来解决这个问题,它遍历 $comments 并添加字段,但是我必须为每个需要 tag_translared 字段的控制器执行此操作。有没有办法让模型包含这样的字段?
回答by Osama Sayed
Add this in your Comment
Model:
将此添加到您的Comment
模型中:
protected $appends = ['tag_translated'];
public function getTagTranslatedAttribute()
{
return 'the translated tag';
}
Hope this helps.
希望这可以帮助。
回答by huuuk
Yes there is? just add this to your Comment
model
就在这里?只需将此添加到您的Comment
模型中
public function getTagTranslatedAttribute()
{
return Lang::methodYouWish($this->tag);
}
then you can access this property from comment instance
然后你可以从评论实例访问这个属性
$comment->tag_translated;
EDIT
编辑
You can modify your toArray
method, just add it to Comment
class
您可以修改您的toArray
方法,只需将其添加到Comment
类
protected $appends = ['tag_translated'];
and then
进而
$comment->toArray();
回答by Daniel Azamar
I was facing the same issue, and you just need to add two things:
我遇到了同样的问题,你只需要添加两件事:
The first one is the appends field:
第一个是 appends 字段:
protected $appends = ['field'];
The second one is the "getter":
第二个是“getter”:
public function getFieldAttribute()
At the end of the method name you need to add the "Attribute" suffix, and that's it.
在方法名称的末尾需要添加“Attribute”后缀,仅此而已。