Spt.php 2.16 KB
<?php

/**
 * @Author: irul
 * @Date:   2019-09-23 13:41:14
 * @Last Modified by:   irul
 * @Last Modified time: 2019-10-01 23:43:21
 */

namespace Integrasi\Reklame\Base\Models;

use \Integrasi\Reklame\Base\Helper;
use \Illuminate\Database\Capsule\Manager as DB;

class Spt extends AbstractModel
{
	protected $table   = 'pad_spt';
	protected $guarded = array();

	protected static function boot()
	{
		parent::boot();
		static::creating(function ($model) {
			return $model->_onCreating();
		});
	}

	public function _onCreating()
	{
		// $maxSptno = Spt::select(DB::raw('max(sptno) as nomor'))
		$maxSptno = call_user_func($this->getParentNamespace() . '\Spt::select',
			DB::raw('max(sptno) as nomor'))
			->where(DB::raw('tahun'), date('Y', strtotime($this->attributes['terimatgl'])))
			->first();
		$sptno = ($maxSptno->nomor ?: 0) + 1;

		$this->attributes['sptno']      = $sptno;
		$this->attributes['create_uid'] = \Api\AuthBasic::getUid();
		return true;
	}

	// == ACCESSORS == //

	public function getSptnoAttribute($value)
	{
		$qry = "select get_sptno(?) as sptno";
		$row = DB::select(DB::raw($qry), array($this->attributes['id']));
		return $row[0]->sptno;
	}

	// == QUERY SCOPES == //

	public static function scopeFindBySptno($query, $sptno)
	{
		return $query->where(DB::raw('get_sptno(id)'), array($sptno));
	}

	public static function scopeFindByKohirno($query, $kohirno)
	{
		return $query->where(DB::raw('get_kohirno(id)'), array($kohirno));
	}

	// == RELATIONSHIPS == //

	/**
	 * Get the customer that owns the spt.
	 */
	public function customer()
	{
		return $this->belongsTo($this->getParentNamespace() . '\Customer');
	}

	/**
	 * Get the kohir record associated with the spt.
	 */
	public function kohir()
	{
		if (!Helper::sptpdExist()) {
			return $this->hasOne($this->getParentNamespace() . '\Kohir');
		}
		return null;
	}

	/**
	 * Get the sspd record associated with the spt.
	 */
	public function sspd()
	{
		return $this->hasOne($this->getParentNamespace() . '\Sspd');
	}

	/**
	 * Get the sptpd that owns the spt.
	 */
	public function sptpd()
	{
		if (Helper::sptpdExist()) {
			return $this->belongsTo($this->getParentNamespace() . '\Sptpd');
		}
		return null;
	}
}