如何为每个产品创建链接(laravel 5.5型号)

时间:2018-02-27 12:33:07

标签: php laravel model

我得到了产品型号,我有link()范围:

public function scopeLink($query) {
        $query->join('categories as children_category', 'products.category_id', '=', 'children_category.id')
            ->join('categories as parent_category', 'children_category.parent_id', '=', 'parent_category.id')
            ->select('products.*','children_category.id as children_cat_id', 'children_category.alias as children_cat_alias','parent_category.id as parent_cat_id', 'parent_category.alias as parent_cat_alias');
        return $query;
    }

它返回一个构建器,它很好,但我需要将链接附加到每个产品集合。我该怎么做?

现在我的产品系列是:

0 => Product {#413 ▼
      #connection: "mysql"
      #table: null
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:18 [▶]
      #original: array:18 [▶]
      #changes: []
      #casts: []
      #dates: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: []
      #touches: []
      +timestamps: true
      #hidden: []
      #visible: []
      #fillable: []
      #guarded: array:1 [▶]
    }

我需要添加属性链接到产品。链接模式是:

$parentCategory.'/'.$childrenCategory.'/'.$productSlug.'-'.$productId.'.html'

1 个答案:

答案 0 :(得分:3)

您可以在模型上使用appends属性向模型添加一些值,当您的模型serializedjson时,这些值会显示,但您需要访问这些属性您正在使用模型内部构建网址

...
protected $appends = ['url'];
...
public function getUrlAttribute()
{
    return $this->attributes['parentCategory'] . $this->attributes['childrenCategory']
       . $this->attributes['productSlug'] . $this->attributes['productId'] . '.html';
}