【问题标题】:How to use relationships in custom attribute inside Eloquent model (Laravel)?如何在 Eloquent 模型(Laravel)中的自定义属性中使用关系?
【发布时间】:2020-05-04 21:14:54
【问题描述】:

你好

我需要在我的 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】:

    您可以在模型中使用 $appends 属性 https://laravel.com/docs/5.6/eloquent-serialization#appending-values-to-json

    protected $appends = ['released'];
    

    【讨论】:

    • 您好,谢谢,但只需添加 $appends 即可解决我的多查询问题?
    • PS:我将资源用于我的 Json 响应
    【解决方案2】:

    我自己解决

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

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

    我得到了集合,对它进行排序并得到第一个模型!

    【讨论】:

      猜你喜欢
      • 2017-04-02
      • 1970-01-01
      • 2023-04-01
      • 2022-01-05
      • 2018-01-21
      • 2015-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多