【问题标题】:Laravel - getting a value from a relationship's attributes as an attribute of the current modelLaravel - 从关系的属性中获取一个值作为当前模型的属性
【发布时间】:2020-01-05 19:20:15
【问题描述】:

我有 2 个模型:汽车和条件

Car 和 Condition 具有一对一的多态关系。条件加入汽车:

class Car extends Model 
{
    // ...

    public function condition()
    {
        return $this->morphOne(Condition::class, 'carable');
    }
}

class Condition extends Model
{
    // ...

    public function carable()
    {
        return $this->morphTo()
    }
}

这将返回以下结构:

{ // car
    "id": 1,
    "condition": {
        "age": "1 year",
        "serviced": "yes"
    }
}

我还想返回汽车级别的age 属性,即

{ // car
    "id": 1,
    "age": "1 year",
    "condition": {
        "age": "1 year",
        "serviced": "yes"
    }
}

我想通过获取汽车模型中的 condition->age 属性来做到这一点。我尝试在 Car 类中设置以下内容:

protected $appends = ["age"];
protected function getAgeAttribute()
{
    return $this->getFinancialAttribute()->getAgeAttribute();
}

以及其他一些变体,但没有成功。有什么办法让我优雅地做到这一点?

【问题讨论】:

  • @dparoli 打错了,现在更新

标签: laravel-5 eloquent eloquent-relationship


【解决方案1】:

您可以尝试将此代码添加到您的Car 模型中:

protected $appends = ['age'];
protected function getAgeAttribute()
{
    return $this->condition->age;
}

但一定要eager load condition 与您的Car 模型一起避免N + 1 查询问题。

$cars = Car::with('condition')->get();

在您的情况下,您可以默认加载将此行添加到您的 Car 模型中:

protected $with = ['condition'];

顺便说一句,您在 Car 模型上的关系应该是这样的:

public function condition()
{
    return $this->morphOne(Condition::class, 'carable');
}

【讨论】:

  • 嗯,这太令人沮丧了——我确信我做对了,但我取消了我的更改并一步一步地按照你的做,他们工作了,谢谢!关于关系 - 我只是快速输入这些(公司政策在此处和其他地方询问时重命名类名等)所以它只是一种类型,关系已经很好,但会更新我的原始帖子!
  • 是的,我在评论后明白这只是一个错字,因为您发布了正确的 json 结果。这就是为什么我还是回答了。
猜你喜欢
  • 2023-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-30
  • 2021-11-19
  • 2020-08-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多