Laravel Accessor按需提供关系

时间:2018-07-04 18:01:02

标签: php laravel accessor

问题:我在Size.php模型中有访问器,与Item.php模型有关联,在API中我需要访问器才能工作,但是在其他控制器中我想禁用访问器。我已从所有文件中删除了不必要/无关的代码。

我想做什么:

在ItemControllerAPI中,我需要访问器才能工作,但是我想在其他控制器中禁用访问器。

我已经看到: 我已经看过这些链接,但对我不起作用。

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

2:Create dynamic Laravel accessor

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

2 个答案:

答案 0 :(得分:2)

我发现了如何做到这一点:

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

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

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

答案 1 :(得分:1)

我建议您在需要时设置__rust_dealloc

$appends