75 lines
1.7 KiB
PHP
75 lines
1.7 KiB
PHP
<?php
|
|
|
|
namespace Modules\Bitrix\Traits;
|
|
|
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
use Illuminate\Database\Eloquent\Relations\MorphOne;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Modules\Bitrix\Models\BitrixId;
|
|
use Illuminate\Database\Eloquent\Relations\HasOne;
|
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
|
|
|
|
|
|
|
|
|
trait Bitrixable
|
|
{
|
|
public function bitrixy(): MorphOne
|
|
{
|
|
return $this->MorphOne(BitrixId::class, 'bitrixable');
|
|
}
|
|
public function bitrixId()
|
|
{
|
|
if ($row = $this->bitrixy()->first())
|
|
{
|
|
return $row->bx_id;
|
|
}
|
|
return false;
|
|
}
|
|
public function setBitrixId($id = null)
|
|
{
|
|
$bitrixy = $this->bitrixy;
|
|
if (!$bitrixy)
|
|
{
|
|
$bitrixId = new BitrixId();
|
|
$bitrixId->bx_id = $id ?? null;
|
|
$this->bitrixy()->save($bitrixId);
|
|
}
|
|
if ($id)
|
|
{
|
|
$bitrixy = $this->bitrixy;
|
|
$bitrixy->bx_id = $id;
|
|
$bitrixy->save();
|
|
}
|
|
return true;
|
|
}
|
|
protected static function create(array $attributes = [])
|
|
{
|
|
$model = new static();
|
|
$model->fill($attributes);
|
|
$model->save();
|
|
$model->setBitrixId();
|
|
return $model;
|
|
}
|
|
|
|
public static function firstOrCreate($attributes = [], $values = [])
|
|
{
|
|
$model = new static();
|
|
foreach ($attributes as $key => $value)
|
|
{
|
|
$model = $model->where($key, $value);
|
|
}
|
|
if ($model->count())
|
|
{
|
|
return $model->first();
|
|
}
|
|
else
|
|
{
|
|
self::create(array_merge($attributes, $values));
|
|
}
|
|
return true;
|
|
}
|
|
}
|
|
|
|
|