E
E
EVOSandru62018-08-15 00:06:24
Laravel
EVOSandru6, 2018-08-15 00:06:24

How valid is a condition on a relation in laravel?

Good afternoon,
There are 2 models - User and Contract( provider_id, customer_id, sign )

class User extends Model {
    public function isProvider()
    {
        return $this->role === 1;
    }

    public function isCustomer()
    {
        return $this->role === 2;
    }

   public function contracts()
    {
        if($this->isProvider())
            return $this->hasMany(Contract::class, 'provider_id');
        if($this->isCustomer())
            return $this->hasMany(Contract::class, 'customer_id');
    }

}

How correct is the implementation of the contracts relationship ?
Does it make sense to inherit Provider and Customer from User and write relationships in them?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
JhaoDa, 2018-08-15
@JhaoDa

Laravel does not care deeply, this is business logic. The problem can only be in the opposite direction if the user is tied to the contract:

// что за юзер — провайдер или потребитель?
// по какому полю строить связь?
$contract->user()->associate($user);
However, apparently, it is enough to make a similar construction with conditions on the other side. But there may be problems: they created an instance of the model, provider_idand customer_iddid not fill it in - what to check in the conditions?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question