如何将产品名称与其单位联系起来?

时间:2018-12-26 09:21:48

标签: php laravel relational-database

这是我的查询:

Branch::active()->ProductUnit()->pluck('name', 'id');

我需要用产品name连接产品unit。我在product模型中也有这样的关系:

public function unit()
{
    return $this->belongsTo(Unit::class);
}

我想在该模型中创建一个范围来处理该混合物:

public function scopeProductUnit(Builder $query)
{
    return $query-> ... ?
}

我应该如何编写该范围以及如何在查询中使用它?

2 个答案:

答案 0 :(得分:0)

在产品模型中使用accessor method

public function getNameWithUnitAttribute()
{
    return $this->name . $this->unit->name;
}

用法:

$product->name_with_unit;

答案 1 :(得分:-1)

您可以append进行回复。将此添加到您的产品模型中

protected $appends = ['name_with_unit'];

然后使用accessor修改数据

public function getNameWithUnitAttribute()
{
    return $this->name . $this->unit->name; // update by your column name
}