<?php
/**
 * BelongsToItem Trait.
 * @version 20/09/16
 * @author Martins Fridenbergs <martins.fridenbergs@mtcmedia.co.uk>
 */

namespace Mtc\Shop\Item;

use Mtc\Shop\Item;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

/**
 * BelongsToItem Trait.
 * Add ability to link any object to item via item_id column
 *
 * @version 20/09/16
 * @author Martins Fridenbergs <martins.fridenbergs@mtcmedia.co.uk>
 */
trait BelongsToItem
{
    /**
     * Scope - ofItem()
     *
     * @param Builder $query Query to extend
     * @param Item $item
     * @return Builder
     */
    public function scopeOfItem(Builder $query, $item)
    {
        return $query->where("item_id", id($item));
    }

    /**
     * Define Eloquent relationship to Item class
     * @return BelongsTo
     */
    public function item()
    {
        return $this->belongsTo(Item::class, 'item_id', 'id');
    }
}