我可以使用名称为“ asset”的belongsTo方法吗?

时间:2019-06-02 17:19:32

标签: laravel eloquent

我有一个模型“ SalesContract”,它与一个名为“ Asset”的类具有“ belongsTo”关系。但是,它不起作用(我无法设置或获取)。

“ 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"
  ]
]

(是,ID为11754的资产确实存在。)

2 个答案:

答案 0 :(得分:0)

默认情况下,关系名称取决于“ foreign_key”

如果要设置与外键不同的关系名称,只需提供外键和other_key以及关系声明

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

答案 1 :(得分:0)

问题解决了。

我不得不从我的__construct()方法中删除以下代码,因为它以某种方式破坏了这种关系:

if (empty($this->number)) {
    if ($asset = $this->asset) {
        $this->number = $asset->external_file_number ?? $asset->internal_file_number;
    }
}