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

如何在Eloquent模型(Laravel)中使用自定义属性中的关系?,laravel,eloquent,model,attributes,eager-loading,Laravel,Eloquent,Model,Attributes,Eager Loading,你好 我需要在我雄辩的模型中做到这一点: protected $with = ['releases']; public function releases() { return $this->hasMany('App\Article\Release', 'article_id'); } public function getReleasedAttribute() { return ($this->releases()->count() > 0); } public fun

你好

我需要在我雄辩的模型中做到这一点:

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);

Thx

您可以在模型中使用$appends属性

我自己决定

我收听“created”事件,在我的主模型上推送一个“released”布尔值,对于我所做的内容:

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

我得到收集,排序,得到第一个模型

您好,thx,但只添加$appends就可以解决我的多查询问题了?PS:我使用资源来响应Json
public function getContentAttribute() {
    return $this->releases->sortByDesc('published_at')->first()->content;
}