Laravel Accessor по требованию на отношения

Проблема: У меня есть аксессор в модели Size.php, которая вызывается в связи с моделью Item.php, в API мне нужен аксессор для работы, но в других контроллерах я хочу отключить аксессор. Я удалил ненужный / не связанный код из всех файлов.

Что я хочу сделать:

В ItemControllerAPI мне нужен аксессор для работы, но я хочу отключить аксессор в других контроллерах.

Я уже видел:
Я уже видел эти ссылки, но у меня не работал.

1: https://laracasts.com/discuss/channels/eloquent/accessor-on-demand-but-not-on-every-results

2: Создать динамический аксессор Laravel

3: https://laracasts.com/discuss/channels/general-discussion/eager-load-accessors

Size.php (модель)

class Size extends Model
{
protected $appends = ['addons'];

public function items()
{
return $this->belongsToMany('App\Item', 'items_sizes')->withPivot('price');//->withTimestamps();
}

public function getAddonsAttribute($value)
{
$addon = Addon::where('addons.category_id', $this->category_id)
->where('size_id', $this->id)
->get();
return $addon;
}
}

Item.php (модель)

class Item extends Model
{
public function options()
{
return $this->belongsToMany('App\Option', 'items_options')->withTimestamps();
}

public function sizes()
{
return $this->belongsToMany('App\Size', 'items_sizes')->withPivot('price');//->withTimestamps();
}
}

ItemControllerAPI.php (Controller)

class ItemControllerAPI extends BaseControllerAPI
{
public function show($id)
{
// If i call the Size model directly by using setAppends([]) its working fine,
// its removing the appended array from Size model

// $size = Size::all();
// $size->each->setAppends([]);
// return $size;

// If i use it with relationship it won't work.

// $itemSingleQuery = Item::with(['sizes' => function($query)
// {
// Doesn't work
// $query->setAppends([]);
// Doesn't work
// $query->each->setAppends([]);
// }])
// ->with('options')
// ->where('id', $id)
// ->get();

// query for getting data with relationships
$itemSingleQuery = Item::with('sizes')
->with('options')
->where('id', $id)
->get();

return $this->respondSuccess('content found', $itemSingleQuery);
}
}

0

Решение

Я хотел бы предложить вам установить $appends когда вам это нужно:

$itemSingleQuery->pluck('sizes')->collapse()->each->setAppends(['addons']);
1

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector