繁体   English   中英

Laravel 按需访问关系

[英]Laravel Accessor on demand on relationship

问题:我在与 Item.php 模型相关的 Size.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(控制器)

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);
    }
}

我已经找到了如何做到这一点:

获取整个集合后,我们需要在每个包含追加的模型中调用setAppends()以在序列化为数组或 JSON 之前添加或删除它们。

$itemSingleQuery = Item::with('sizes')->get();

$itemSingleQuery->each(function ($item) {
    $item->sizes->each->setAppends(['addons']);
});

我建议您在需要时设置$appends

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

暂无
暂无

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

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