简体   繁体   English

Laravel 5.5中的Pivot-Column访问器

[英]Accessor for Pivot-Column in Laravel 5.5

My database looks like this: 我的数据库看起来像这样:

dishes (id, image) 菜肴 (身份证,图片)

dish_location (location_id, dish_id, dishcard_sharing) dish_location (location_id,dish_id,dishcard_sharing)

locations (id, name) 地点 (身份证,姓名)

The columns image and dishcard_sharing are both paths like /images/1234/123123.jpg . 图像dishcard_sharing都是像/images/1234/123123.jpg这样的路径。 For the dishes.image-column I just added an accessor to prepend the S3-url. 对于dishes.image-column,我刚添加了一个访问器来添加S3-url。 Now I need such an accessor for the dish_location.dishcard_sharing colunm too. 现在我也需要dish_location.dishcard_sharing colunm这样的访问器。 But where to implement it? 但是在哪里实施呢?

<?php

namespace App\Models;

use DB;
use Illuminate\Database\Eloquent\Model;
use Grimzy\LaravelMysqlSpatial\Types\Point;
use App\Models\DishLocationPivot;

class Dish extends Model
{
    public $table_name = 'dishes';

    public function locations() {
        return $this
          ->belongsToMany('App\Models\Location', 'dish_location', 'dish_id', 'location_id')
          ->withPivot(['dishcard_sharing']);
    }

    /* Accessors */
    public function getImageAttribute($value) {
        return config('filesystems.store_url_prefix') . $value;
    }

    public function scopeFinalize($query) {

      // Dish Card?
      $query->addSelect('dish_location.dishcard_sharing AS dishcard_sharing');
      return $query;
    }
}

One option is to create a new class that extends the Pivot: 一种选择是创建一个扩展Pivot的新类:

use Illuminate\Database\Eloquent\Relations\Pivot;

class DishLocation extends Pivot {
   ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM