简体   繁体   中英

Accessor for Pivot-Column in Laravel 5.5

My database looks like this:

dishes (id, image)

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 . For the dishes.image-column I just added an accessor to prepend the S3-url. Now I need such an accessor for the dish_location.dishcard_sharing colunm too. 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:

use Illuminate\Database\Eloquent\Relations\Pivot;

class DishLocation extends Pivot {
   ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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