Laravel检索单个相关属性

时间:2018-04-18 10:39:16

标签: laravel api laravel-5 eloquent relationships

我有一个允许用户发帖的laravel应用。每个帖子都有一个价格(存储为整数),属于一所大学,而大学又属于一个拥有货币的国家。

每次我检索帖子时,我都想退还货币。我可以做with('university.country'),但这将返回大学和国家的所有细节。

我可以添加一个getCurrencyAttribute并在那里定义逻辑,但这似乎不是mutators的用途,特别是因为如果我收到所有帖子,每个帖子将进一步运行两个自己的查询只是为了得到货币。这3个查询可以获得一个帖子,这可以在返回10个以上的帖子时迅速收回费用。

public function getCurrencyAttribute() {
        return $this->university->country->currency;
    }

    public function getPriceAttribute($value) {
        return "{$this->currency}{$value}";
    }

^上面的例子:不需要appends,因为price会被自动覆盖。这是在DebugBar上看到的问题(在Post模型上调用了两个新查询,虽然预期在检索大量帖子时效率低下): enter image description here

每次获得单个相关字段的最佳方式是什么?

Full code on GitHub.

1 个答案:

答案 0 :(得分:0)

您可以限制预先加载的列:

Post::with('webometricUniversity:uni-id,country_id',  
    'webometricUniversity.country:id,currency')->get();

如果您总是需要它,请将其添加到您的Post型号:

protected $appends = ['currency'];

protected $with = ['webometricUniversity:uni-id,country_id',  
    'webometricUniversity.country:id,currency'];

public function getCurrencyAttribute() {
    return $this->webometricUniversity->country->currency;
}

然后您可以使用Post::get()$post->currency

相关问题