Могу ли я использовать метод ownTo с именем 'asset'? - PullRequest
0 голосов
/ 02 июня 2019

У меня есть модель «SalesContract», которая имеет отношение «ownTo» с классом «Asset».Тем не менее, он не работает (я не могу установить или получить).

Может ли быть проблема с вспомогательным методом "asset ()"?

Если я изменю имя моего метода начто-то вроде «related_asset ()», тогда это работает.

Это НЕ работает:

public function asset()
{
    return $this->belongsTo(Asset::class);
}

Это работает:

public function related_asset()
{
    return $this->belongsTo(Asset::class);
}

Полная модель:

class SalesContract extends Model
{
    use SoftDeletes;
    use Commentable;

    const icon_class = 'far fa-file-signature';

    const default_buyer_fee = 100;
    const default_carproof_fee = 36.45;

    protected $fillable = [
        'number', 'asset_id', 'seller_id', 'buyer_id', 'buyer_representative', 'sale_date', 'sale_price',
        'apply_sales_taxes_to_sale_price', 'buyer_fee', 'carproof_fee', 'deposit'
    ];

    protected $casts = [
        'sale_date' => 'datetime',
        'sale_price' => 'float',
        'carproof_fee' => 'float',
        'buyer_fee' => 'float',
        'deposit' => 'float',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
        'deleted_at' => 'datetime'
    ];

    protected $appends = [
        'subtotal', 'taxable_amount', 'sales_taxes', 'total', 'balance'
    ];

    protected static function boot()
    {
        parent::boot();

        static::addGlobalScope('order', function (Builder $builder) {
            $builder->orderBy('created_at', 'desc');
        });

        static::saving(function($table) {
            if (empty($table->id)) {
                if ($current_user = Auth::user()) {
                    $table->created_by_user_id = $current_user->id;
                }
            }
        });
    }

    public function __construct(array $attributes = [])
    {
        if (empty($this->sale_date)) {
            $this->sale_date = Carbon::today()->format('Y-m-d');
        }

        if (empty($this->id)) {
            if (empty($this->number)) {
                if ($asset = $this->asset) {
                    $this->number = $asset->external_file_number ?? $asset->internal_file_number;
                }
            }
            $this->buyer_fee = $this->buyer_fee ?? self::default_buyer_fee;
            $this->carproof_fee = $this->carproof_fee ?? self::default_carproof_fee;
            $this->apply_sales_taxes_to_sale_price = $this->apply_sales_taxes_to_sale_price ?? 1;
        }

        parent::__construct($attributes);
    }

    public function __toString()
    {
        return __('sales_contracts.item_label', ['number' => $this->number ?? $this->id]);
    }

    public function scopeFilter($query, $filters)
    {
        $filters = is_array($filters) ? array_filter($filters) : [];
        return $query->where($filters);
    }

    public function asset()
    {
        return $this->belongsTo(Asset::class);
    }

    public function seller()
    {
        return $this->belongsTo(Contact::class);
    }

    public function buyer()
    {
        return $this->belongsTo(Contact::class);
    }

    public function created_by_user()
    {
        return $this->belongsTo(User::class);
    }

    public function getSubtotalAttribute()
    {
        return $this->sale_price + $this->carproof_fee + $this->buyer_fee;
    }

    public function getTaxableAmountAttribute()
    {
        if ($this->apply_sales_taxes_to_sale_price) {
            return $this->subtotal;
        } else {
            return $this->subtotal - $this->sale_price;
        }
    }

    public function getSalesTaxesAttribute()
    {
        $sales_taxes = [];
        if ($seller = $this->seller) {
            foreach ($seller->sales_tax_numbers as $tax_number) {
                if ($tax_number->use) {
                    if ($sales_tax = $tax_number->sales_tax) {
                        $sales_taxes[] = [
                            'sales_tax' => $sales_tax,
                            'name' => $sales_tax->name,
                            'rate' => $sales_tax->rate,
                            'label' => $sales_tax->label,
                            'number' => $tax_number->number,
                            'amount' => round($this->taxable_amount * $sales_tax->rate, 2)
                        ];
                    }
                }
            }
        }
        return $sales_taxes;
    }

    public function getSalesTaxesTotalAttribute()
    {
        $total = 0;
        foreach ($this->sales_taxes as $sales_tax) {
            $total += $sales_tax['amount'];
        }
        return $total;
    }

    public function getTotalAttribute()
    {
        return $this->subtotal + $this->sales_taxes_total;
    }

    public function getBalanceAttribute()
    {
        return $this->total - $this->deposit;
    }
}

От контроллера:

$sales_contract = new SalesContract;

if ($request->has('sales_contract')) {
    $sales_contract->fill($request->input('sales_contract'));
}

Результат dd($request->input()):

array:1 [▼
  "sales_contract" => array:1 [▼
    "asset_id" => "11754"
  ]
]

(Да, актив с идентификатором 11754 существует.)

Ответы [ 2 ]

0 голосов
/ 02 июня 2019

Проблема решена.

Мне пришлось удалить следующий код из моего __construct() метода, так как он как-то нарушал отношения:

if (empty($this->number)) {
    if ($asset = $this->asset) {
        $this->number = $asset->external_file_number ?? $asset->internal_file_number;
    }
}
0 голосов
/ 02 июня 2019

по умолчанию Имя отношения зависит от 'foreign_key'

если вы хотите установить другое имя отношения, чем внешний ключ, просто укажите внешний ключ и other_key вместе с объявлением отношения

public function asset()
{
    return $this->belongsTo(Asset::class,related_asset,id);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...