如何在Eloquent模型(Laravel)中使用自定义属性的关系?

问题描述 投票:1回答:1

你好

我需要在我的Eloquent模型中这样做。

protected $with = ['releases'];
public function releases() { return $this->hasMany('App\Article\Release', 'article_id'); }
public function getReleasedAttribute() { return ($this->releases()->count() > 0); }
public function getContentAttribute() { return $this->releases()->orderBy('published_at', 'desc')->first()->content; }

但是,我有很多的查询调用!!!!!!!!!!!!"。什么是最好的解决方案来急切加载?我每次都需要这些属性,所以我更喜欢直接在我的模型中设置,而不是在我的控制器中的查询生成器上设置。

我使用一个自定义的资源为我的Json响应和这里的查询我的控制器上。

$articles = Article::with('releases')->has('releases')->get();
return ArticleReleasedResource::collection($articles);

谢谢

laravel eloquent model attributes eager-loading
1个回答
2
投票

你可以在你的模型中使用$appends属性。https:/laravel.comdocs5.6eloquent-serialization#appending-values-to-json。

protected $appends = ['released'];

0
投票

我自己解决

我监听 "创建 "事件,以推动 "发布 "布尔值在我的主模型,并为我做的内容。

public function getContentAttribute() {
    return $this->releases->sortByDesc('published_at')->first()->content;
}

我得到集合,对其进行排序,并得到第一个Model !

© www.soinside.com 2019 - 2024. All rights reserved.